Parsing json into Java Pojos with Gson called from Kotlin is missing generic information


#1

I’m having an issue with Java types and Gson, when being called from Kotlin

The Java POJO’s representing an API response and it’s errors

public class ApiResponse {

  @SerializedName("errors")
  public List<ApiResponseError> errors;
}


public class ApiResponseError {

  @SerializedName("code")
  public Integer code;

  @SerializedName("message")
  public String message;
}

The http response body on the wire

{
  "errors": [
    {
      "code": 10002,
      "message": "Not found"
    }
  ]
}

The kotlin code using Gson to parse the response into objects.

val errorResponse = Gson().fromJson<ApiResponse>(jsonBody, ApiResponse::class.java)

jsonBody is the string representation of the http response body on the previous snippet.

The debugger view of instantiated objects:

enter image description here

The problem is that the ArrayList should contain a ApiResponseError object and not a LinkedTreeMap.

I tried the same code without the generic type on the List<ApiResponseError> errors list, and the result is the same, so I am guessing the generic information is being lost somewhere and Gson is defaulting to LinkedTreeMap.

Any clues or references I can take a look?

Thanks


#2

How does it work when calling this from Java code? Is this only an issue when invoking GSon from Kotlin code?

Did you try converting the API classes to Kotlin, does that affect the result?

I don’t recall seeing such issues when using JacksonJsonMapping; is it an option for you to try this out at least?

And what runtime and Java version are you using? Is this on Android, or not?


#3

I assume by your syntax you are trying to use Kotson, in which case you do not want the class parameter

val errorResponse = Gson().fromJson<ApiResponse>(jsonBody)

#4

Apparently, setting @JvmSuppressWildcards to errors field should solve the issue. See https://github.com/google/gson/issues/1101