Kotlin Users: Safely Upgrade to Moshi
If you’re still using Gson there has never been a better time to make the jump to Moshi. With the newly added Kotlin Code Generation artifact, Moshi’s laundry list of benefits over Gson keeps growing. To help Retrofit 2 users get off Gson, let’s take a look at a simple but safe upgrade path that lets you migrate endpoints one-by-one.
Annotate Your Endpoints
Start by rolling a
@Moshi annotation and applying it to service methods you want to be Moshi enabled.
Create a Migration Converter
Then roll a
Converter.Factory that checks to see if a service method is annotated
Plug in Your Migration Converter
Lastly, plug your migration converter into your
Retrofit instance. Your gson converter must come after the migration converter.
That’s it! You can now annotate any service method with
@Moshi and Moshi will be used for serializing request and response bodies! Drop me a comment and let me know how you plan to upgrade to Moshi.
Attribution: This pattern was originally developed by Jake Wharton. A more robust version of an annotation based
Converter.Factory written by Eric Cochran can be found here. Special thanks to Eric for collaborating with me on this post.