Thursday 19 November 2020

Best way to integrate MoShi and Retrofit 2 in an Android Studio project

I would like to know what is the best way to integrate Retrofit with MoShi on my Android Studio project.

First of all, I use the moshi converter of retrofit :

implementation 'com.squareup.retrofit2:converter-moshi:2.9.0'

I use the popular plugin "Json to Kotlin class" for the generation of my POJO : https://plugins.jetbrains.com/plugin/9960-json-to-kotlin-class-jsontokotlinclass-

When I create a new POJO, I use the annotation "MoShi (Reflect)" : enter image description here

It generate me a Pojo with fields like this one :

@Json(name = "image_url")
val imageUrl: String?

The problem is Retrofit2 seem don't like underscore in my fields name because I get null results with the underscored names.

Searching in the Github issues, I found a solution. It work if I use this annotation :

@field:Json(name = "image_url")
val imageUrl: String?

So my questions are :

  1. Using the @field:Json annotation is the best way to use MoShi with Retrofit ?
  2. If yes, how to generate easily a Kotlin class with this annotation (using the same plugin or an other) ?


from Best way to integrate MoShi and Retrofit 2 in an Android Studio project

No comments:

Post a Comment