Trello Android not too long ago transformed from utilizing Gson to Moshi for dealing with JSON. It was a bit tough so I wished to doc the method.
(For context, Trello Android primarily parses JSON. We hardly ever serialize JSON, and thus many of the focus right here is on deserializing.)
There have been three principal causes for the swap from Gson to Moshi: security, velocity, and unhealthy life selections.
Security – Gson doesn’t perceive Kotlin’s null security and can fortunately place null values into non-null properties. Additionally, default values solely generally work (relying on the constructor setup).
Pace – Loads of benchmarks (1, 2, 3) have demonstrated that Moshi is often quicker than Gson. After we transformed, we arrange some benchmarks to see how real-world parsing in contrast in our app, and we noticed a 2x-3.5x speedup:
Dangerous life selections – As an alternative of utilizing Gson to parse JSON into easy fashions, we’d write elaborate, complicated, brittle customized deserializers that had solely an excessive amount of logic in them. Refactoring gave us a possibility to appropriate this architectural snafu.
As for why we picked Moshi over rivals (e.g. Kotlin serialization), we usually belief Sq.’s libraries, we have used Moshi prior to now for tasks (each at work and at residence) and felt it labored nicely. We didn’t do an in-depth examine of options.
Step one was to make sure that we might use function flags to change between utilizing our outdated Gson implementation and the brand new Moshi one. I wrote a JsonInterop
class which, based mostly on the flag, would both parse all JSON responses utilizing Gson or Moshi.
(I opted to keep away from utilizing instruments like moshi-gson-interop as a result of I wished to check whether or not Moshi parsing labored in its entirety. For those who’d relatively have a mixture of Gson and Moshi on the similar time, that library could be helpful.)
Gson offers you alternatives to override the default naming of a key utilizing @SerializedName
. Moshi permits you to do the identical factor with @Json
. That is all nicely and good, however it appeared very easy to me to make a mistake right here, the place a property is parsed underneath totally different names in Gson vs. Moshi.
Thus, I wrote some unit assessments that may confirm that our generated Moshi adapters would have the identical final result as Gson’s parsing. Particularly, I examined…
- …that Moshi might generate an adapter (not essentially an accurate one!) for every class we wished to deserialize. (If it could not, Moshi would throw an exception.)
- …that every area annotated with
@SerializedName
was additionally annotated with@Json
(utilizing the identical key).
Between these two checks, it was simple to seek out once I’d made a mistake updating our lessons in later steps.
(I can’t embody the supply right here, however mainly we used Guava’s ClassPath to collect all our lessons, then scan via them for issues.)
Gson permits you to parse generic JSON bushes utilizing JsonElement (and buddies). We discovered this convenient in some contexts like parsing socket updates (the place we wouldn’t understand how, precisely, to parse the response mannequin till after some preliminary processing).
Clearly, Moshi shouldn’t be going to be glad about utilizing Gson’s lessons, so we switched to utilizing Map
(and generally Listing
) for generic bushes of information. Each Gson and Moshi can parse these:
enjoyable fromJson(map: Map?, clz: Class): T? {
return if (USE_MOSHI) {
moshi.adapter(clz).fromJsonValue(map)
}
else {
gson.fromJson(gson.toJsonTree(map), clz)
}
}
As well as, Gson is pleasant in direction of parsing by way of Readers, however Moshi shouldn’t be. I discovered that utilizing BufferedSource was various, as it may be transformed to a Reader for outdated Gson code.
The best adapters for Moshi are those the place you simply slap @JsonClass
on them and name it a day. Sadly, as I discussed earlier, we had quite a lot of unlucky customized deserialization logic in our Gson parser.
It’s fairly simple to write a customized Moshi adapter, however as a result of there was a lot customized logic in our deserializers, simply writing a single adapter wouldn’t minimize it. We ended up having to create interstitial fashions to parse the uncooked JSON, then adapt from that to the fashions we’re used to utilizing.
To present a concrete instance, think about now we have a knowledge class Foo(val depend: Int)
, however the precise JSON we get again is of the shape:
{
"knowledge": {
"depend": 5
}
}
With Gson, we might simply manually take a look at the tree and seize the depend out of the knowledge
object, however now we have found that means lies insanity. We might relatively simply parse utilizing easy POJOs, however we nonetheless wish to output a Foo ultimately (so we do not have to vary our complete codebase).
To unravel that drawback, we’d create new fashions and use these in customized adapter, like so:
@JsonClass(generateAdapter = true) knowledge class JsonFoo(val knowledge: JsonData)
@JsonClass(generateAdapter = true) knowledge class JsonData(val depend: Int)
object FooAdapter {
@FromJson
enjoyable fromJson(json: JsonFoo): Foo {
return Foo(depend = json.knowledge.depend)
}
}
Voila! Now the parser can nonetheless output Foo, however we’re utilizing easy POJOs to mannequin our knowledge. It’s each simpler to interpret and simple to check.
Bear in mind how I stated that Gson will fortunately parse null values into non-null fashions? It seems that we have been (sadly) counting on this habits in all kinds of locations. Particularly, Trello’s sockets typically return partial fashions – so whereas we’d usually anticipate, say, a card to return again with a reputation, in some circumstances it received’t.
That meant having to watch our crashes for circumstances the place the Moshi would blow up (as a consequence of a null worth) when Gson could be glad as a clam. That is the place function flags actually shine, because you don’t wish to need to push a buggy parser on unsuspecting manufacturing customers!
After fixing a dozen of those bugs, I really feel like I’ve gained a hearty appreciation for non-JSON applied sciences with well-defined schemas like protocol buffers. There are quite a lot of bugs I bumped into that merely wouldn’t have occurred if we had a contract between the server and the consumer.