1

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

David Soroko
  • 8,521
  • 2
  • 39
  • 51

2 Answers2

2

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)]
}

David Soroko
  • 8,521
  • 2
  • 39
  • 51
-1

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.

shadowsheep
  • 14,048
  • 3
  • 67
  • 77
  • hi @shadowsheep , thank you for the suggestion :), I actually need to deserialize the array of values into an object, we are trying to reduce the data usage so we get the values in arrays the same I asked for. Is there any way to do that? – avinash sai pavan munnangi Dec 15 '20 at 12:57
  • @avinashsaipavanmunnangi this is a non standard way of deserialize an object. Actually, the first thing that comes to my mind is to deserialize it as an array of strings and then write your custom mapping function that create your objects. – shadowsheep Dec 15 '20 at 13:19