Kevin Gozali
Kevin Gozali

Reputation: 319

Cannot Deserialize Generic Type T Moshi

Sorry if this is a basic question, but i'm new to Moshi.

So, I have a class with Generic Type Paramter as follows:

class BaseResponse<T> {
   @Json(name = "message")
   var message: String? = null
   @Json(name = "data")
   var data: T? = null
   @Json(name = "meta")
   var meta: JsonObject? = null
   @Json(name = "error")
   var error: ErrorResponse? = null
}

In GSON, this is done automatically and it works as long as i provide @SerializedName("data") and extends BaseResponse in my retrofit method. But it returns error with moshi as i could not deserialize BaseResponse. How can i fix this?

Upvotes: 1

Views: 647

Answers (2)

Nikos M
Nikos M

Reputation: 194

Both base class and class that replace generic type in code must be annotated with @JsonClass(generateAdapter = true). Please notice that the most important thing in order json to be converted correctly to a model class such as this, is to declare fields at base class as var and NOT as val. Please look the example below:

 @JsonClass(generateAdapter = true)
 class BaseResponse<T> {

   @Json(name = "message")
   var message: String? = null
   @Json(name = "data")
   var data: T? = null
   @Json(name = "meta")
   var meta: JsonObject? = null
   @Json(name = "error")
   var error: ErrorResponse? = null
}

Api example:

@GET("api/info")
suspend fun getInfo(): BaseResponse<Info>

Info:

@JsonClass(generateAdapter = true)
data class Info(
    val language: String? = null,
    val profile: Profile? = null
)

Upvotes: 4

92AlanC
92AlanC

Reputation: 1387

In Moshi you have to explicitly declare your annotations as field annotations, like @field:Json(name = "message")

Upvotes: 1

Related Questions