Home > Blockchain >  How to use json array in Kotlin Using Moshi
How to use json array in Kotlin Using Moshi

Time:09-29

[{"id":1,"first_name":"Lillis","last_name":"Hawgood"," cars":[ {"item":"Savana 1500"}, {"item":"Vibe"}, {"item":"Estate"} ]}]

data class MyData( val id: Int = 0, val first_name: String = "", val last_name: String = "", val cars: List

)

class Car { @Json(name = "item") var item: String? = null How to use Item in Data class the how ot print in main clas using moshi txtResult.text = "" for (myDataLst in myDataList ?: emptyList()) { txtResult.append("${myDataLst.first_name} - ${myDataLst.last_name} - ${myDataLst.cars} \n") }enter code here

I tried this way only first name and last showing but for cars showing some worng infor

CodePudding user response:

Try this data classes i transform it using Json to Data Class plugin.

data class MyData(
    val  cars: List<Car>,
    val first_name: String,
    val id: Int,
    val last_name: String
)

data class Car(
    val item: String
)

class car  : ArrayList<MyData>()

CodePudding user response:

Firstly, please format your code, it's hard to read your code.

Secondly, you can use the Moshi like this:

@JsonClass(generateAdapter = true)
data class MyData(
        @Json(name = "id") val id: String,
        @Json(name = "first_name") val firstName: String,
        @Json(name = "last_name") val lastName: String,
        @Json(name = "cars") val cars: List<Car>
)

@JsonClass(generateAdapter = true)
data class Car(
    @Json(name = "item") val item: String
)
  • Related