Goodbye Gsonš, Hello Moshiš¤
Time to migrate your Android projects from Gson to Moshi and say Adios Gson

OK, Itās been a while, We had a good time together, but itās time to move-on now!
You might have heard this sentence (hopefully not!) in your relationships, but this article is not about that topic, itās about moving on to a new serialization library for Android and Kotlin! Migrating from Gson to Moshi!
Make sure to continue reading part 2 of this article:
So before we get started on why Moshi is a better option and how should we migrate to using it letās see howās Gson doing nowadays:
Gson, What?
If we look at itās Github repository the description says:
A Java serialization/deserialization library to convert Java Objects into JSON and back
ā Which obviously is not Kotlin-Friendly or written in Kotlin, So one can clearly understand that this is not a Modern library anymore. Itās been out there since 2008, So itās been 12 years, and it seems not being updated anymore. Dead projectā ļøā ļø!

ā It has not been updated recently, And the last commits donāt seem to be like a huge update or bug fix:

It actually makes sense to not to touch something thatās working perfectly fine and break the library thatās used by millions of apps out there, but current situation with Gson is different, Seems to be just dead project.
ā Method count wise, Gson has ~1036 methods which are almost twice as Moshi (~500)!
ā Footprint wise, Gson adds ~300kB to your APK size compared to ~120kB!
āGson only can use reflection to serialize/deserialize JSON strings. Compared to Moshiās Kotlin code-gen support.
āGson does not support default values for fields, If a field is missing in the response JSON string and youāve set its default value to something rather than null, It will be null afterwards!
So letās suppose Gsonās dead, Where should we go from here? We can continue using Gson forever, itās working! but for the curious developers out there and Kotlin lovers, thereās Moshi as well! So letās see Whatās Moshi and why?
Moshi, Who?
A modern JSON library for Kotlin and Java.
Moshiās repo at Githubās description. And man, Thatās lovely! Itās modern, Kotlin friendly, fast, reliable with lots of features. Letās review some of Moshiās features:
ā Better API:
Moshi offers better and more modern API you can do neat things using this super powerful API.
Annotations are called āfirst-class partā Moshi, This allows you to put some information in them which leads to more fine-grained and contextual deserialization.
- You can create annotations of your own to customize parsing of a field in your JSON data, (@ColorInt @FromHexColor int colour)
- Custom adapters or Contextual Deserialization which leads to neat features that cause less boilerplate code (Lazy adapters)
- Moshi has better and more human-readable serialization failed messages, This is a huge plus when the appās published and you receive weird stack traces that you have no idea what you should do about
- Moshi has a newBuilder() API which can be used to create new adapters from upstream adapters, Something similar to OkHttp or Okio builders, This is super helpful because you can create separate adapters so you donāt end up with having a god adapter which knows how to parse 1K+ models.
- Moshi has built-in support for polymorphic datatypes which also has fallback support for unknown types!
- Moshi has Code-gen adapter for Kotlin, This is great! With help of annotations, you make the Serialization/Deserialization much faster and bypass the old slow reflection method that Gson uses!
ā Performance
Moshi is way faster than Gson(Link1, ) and uses less memory, This is due to its usage of Okio which can predict or expect ahead of the time the keys which helps on ignoring the unknown or unwanted fields while parsing a stream (A good article on this). Retrofit is also using Okio under the hood, So guess what happens? The JSON serialization library(Moshi) and networking library(Retrofit) are sharing the buffer their using which leads to much lower memory consumption while making network calls and serializing the response!
Enough with the theory, Show me the codeš§āš»
OK, Letās see how migrationās done step by step:
1- add dependencies into your build.gradle file:
2- Replace all @SerializedName annotations with @Json:
To:
3- Add @JsonClass(generateAdapter = true) annotation to all data classes
Add @JsonClass(generateAdapter = true) annotation to all data classes Which are going to participate in the serializing/deserializing JSON process. This helps Moshi to use code-gen and not to use reflection which will increase the speed of the process:
4- Change Gson instances to Moshi
If youāre using Dagger to provide dependencies you might have something like:
This needs to be changed to:
5- Change converter used in creating Retrofit
If youāre using Retrofit, and also Dagger, you probably have something similar:
Which will be refactored to:
Thatās it! This was a simple case of refactoring Gson to Moshi. There are some cases that Moshi handles a bit differently but this should be good for simple usages.
Letās see some cases that are handled a bit different in Moshi, These are cases that you might face after removing Gson from your current projects and replace it with Moshi.
Case #1 ā Alternate keys:
There are cases that a field in the JSON response might have a few different keys, This case was handled in this fashion using Gson:
So you just needed to add other keys in the alternate array field and you were good to go, but itās a bit different in Moshi:
First, you need to add a qualifier annotation for the field you're trying to serialize:
Then you will need to create an intermediate class with those alternative keys:
Then we will create another class named Id which will hold the id field:
Now letās change the field type from Long to Id in original field when we were using Gson, So it becomes like:
Weāre almost done now we need to define a custom JSON adapter and add it to Moshi instance, Letās create the adapter first:
Cool, Now letās add this fancy adapter to out Singletone Moshi instance:
Thatās it, We just needed a few more steps to achieve alternative keys than Gson š
Fore more complex cases read next part of the article:
Case #2: Serializing enums:
Case #3: Manual Serializing an object
Case #4: Manual Serializing list of objects
Case #5: Parsing Polymorphic JSON list
Alright, Thatās it for now, please let me know what do you think or you have any problems or difficulties while migrating from Gson to Moshi.
Great job on making it to the end of this article! šŖ
- Follow my YouTube channel for video tutorials and tips on Android development
- If you need help with your Android project, Book a 1:1 or a Pair-Programming meeting with me, 100% free! book a time here š
If you like this article please can you do me a little favour and hit the šclap button as many times! I really appreciate your kindness xā¤ļøš
You might be interested in the following article as well:
References/Read more: https://www.reddit.com/r/androiddev/comments/684flw/why_use_moshi_over_Gson/