How to parse un json string into a List with MOSHI

Viewed 2575

I'm looking to parse a a result json who built like that :

{"list": [
        {
            "data1": "data1",
            "transaction": {
                "data2": "data2",
                "data3": "data3"
            },
            "breakdowns": [
                {
                    "data4": "data4",
                    "data5": "data5"
                }
            ]
        }
]}

I'm using moshi and okHttpClient to handle this json. I build the data class correclty

So now when I try to parse it (like that) :

 200 -> {
val moshi = Moshi.Builder()
.add(KotlinJsonAdapterFactory())
.build()

val type: Type = Types.newParameterizedType(List::class.java,PaymentRequest::class.java)

try{
   val q: JsonAdapter<List<PaymentRequest>> = moshi.adapter(type)
   paymentRequest = q.fromJson(response.body!!.source())!!
}catch (e: Exception) {
   println(e)
}

}

And I got this error : com.squareup.moshi.JsonDataException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at path $

1 Answers

You can't treat this json as a list. It's not a list itself but actually is a json object that contains a list.

To solve that, first build a class to wrap the "list":

@JsonClass(generateAdapter = true)
data class Wrapper(@Json(name = "list") val list: List<PaymentRequest>)

Then you are good to go:

val moshi = Moshi.Builder()
    .add(KotlinJsonAdapterFactory())
    .build()
val adapter = moshi.adapter<Wrapper>(Wrapper::class.java)
val paymentRequests = adapter.fromJson(response.body!!.source())!!.list
Related