How to parse a json string to a List with MOSHI

6.4k views Asked by At

I'm looking to parse the below JSON:

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

I'm using Moshi and okHttpClient to handle this JSON. My data class is correct

But when I try to parse it as below:

val moshi = Moshi.Builder()
  .add(KotlinJsonAdapterFactory())
  .build()

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

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

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

2

There are 2 answers

0
Sơn Phan On BEST ANSWER

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
0
Ashwani On

It worked for me, Convert Json to List in Moshi

@TypeConverter
    fun toListAWDataItem(json: String): List<Person>? {
        val type: Type = Types.newParameterizedType(
            List::class.java,
            Person::class.java
        )
        val adapter: JsonAdapter<List<Person>> = moshi.adapter<List<Person>>(type)
        return adapter.fromJson(json)!!.map { it }
    }