Moshi Made Simple: @JsonQualifier

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 moshiBuilder.add(EnvelopeFactory.INSTANCE):

For the JSON blob above, instead of returning a wrapper object, my Retrofit API now looks like:

Where Securities holds a reference to a list of Security objects.

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 @JsonQualifer!

Written by

Simplicity is the ultimate sophistication.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store