Moshi has some nice bells and whistles that aren’t present in Gson. One of my favorite ones is
@JsonQualifier. This feature lets you roll custom annotations that control how deserialization is performed.
Recently I was working with an API that would wrap all its responses inside an extra JSON Object:
Deserializing this blob required creating a wrapper object,
SecuritiesResponse, which had a field named
securities. As I started using more endpoints with similar semantics, I ended up having to create an extra wrapper object per endpoint — yuck!
@JsonQualifier to the Rescue
To avoid this, I rolled a custom annotation that could be tacked onto any Retrofit API:
I then wrote a custom
JsonAdapter.Factory that handles deserializing endpoints annotated with
@Enveloped and plugged it into my Moshi instance using
For the JSON blob above, instead of returning a wrapper object, my Retrofit API now looks like:
Securities holds a reference to a list of
I love qualifiers for handling custom deserialization semantics like this because they’re easy to write and can be reused across endpoints. Drop me a comment and let me know your favorite use cases for