Home > Mobile >  Serialize any type of list item
Serialize any type of list item

Time:08-04

I have this Any type of list;

val sendMetas = mutableListOf<Any>()
sendMetas.add(CarType(count = "2",type = 2))

When sending to the server it should go like this;

"Metas": [{
"car_type": {
    "count": "1",
    "type": 3
}}]

But instead, it goes like this;

"Metas":[{"count":"2","type":2}]

How can I surround with serialize name I have couple more objects like CarType. Thanks.

CodePudding user response:

I handled by turning into JsonObject;

 val jsonObject = JsonObject()
 jsonObject.addProperty("count", "1")
 jsonObject.addProperty("type", 3)

 val prepTimeJson = JsonObject()
 prepTimeJson.add("car_type", jsonObject)
 sendMetas.add(prepTimeJson)

CodePudding user response:

"Metas" field in exptected json is array of "Meta" object, so instead of adding "CarType" instances in "sendMetas" array you should create "Meta" (data)class with "car_type" field, so it'll look like that:

data class Meta (
  val car_type: CarType
)

data class CarType (
  val count: String,
  val type: Int
)

val sendMetas = mutableListOf<Meta>()
sendMetas.add(Meta(car_type = CarType(count = "2",type = 2)))

CodePudding user response:

check this once use this link for serialize or model class.

https://www.jsontodart.in/

  • Related