How to deserialize an array of values into a collection using kotlinx serialization

4.5k Views Asked by At

Hi I am a newbie to kotlinx serialization and I am using KMP, my requirement is a little different

my data class

@Serializable data class Student(val name : String , val age : Int)

and my simple JSON would be "['Avinash', 22]",

which should be deserialized to Student("Avinash", 22)

I'm not able to deserialize it can anyone help me

2

There are 2 best solutions below

2
On

Try this:

val student: Student = Json.decodeFromString("{\"name\": \"Avinash\", \"age\": \"22\"}")

Pay attention how to format your JSON string.

  • [] square brackets are for arrays
  • {} curly brackets are for objects

And you must provide your fields name, and use double quotes for fields and values, or use a less strict Json deserialization:

val json = Json {
    isLenient = true
}
val student: Student = json.decodeFromString("{name: Avinash, age: 22}")

If you want a deep view on json schema, you can read here.

0
On

While input such as [Avinash, 22] is not well formed Json, you can still work with it by parsing it into a JsonElement:

import kotlinx.serialization.json.*

data class Student(val name: String, val age: Int)

fun decode(stringData: String, parser: Json): List<Student> {
    val element: JsonArray = parser.parseToJsonElement(stringData).jsonArray
    return element.windowed(2, 2).map {
        Student(
            it[0].toString(),
            it[1].toString().toInt()
        )
    }
}

fun main() {
    val parser = Json { isLenient = true }
    val students = decode("[A, 22, B, 33, C, 44]", parser)
    println(students)
    // [Student(name=A, age=22), Student(name=B, age=33), Student(name=C, age=44)]
}