jsonparsingkotlinkotlinx.serialization

Parse a nested JSON with Kotlinx.Serialization


I've been playing with Kotlinx.serialization, and I have been trying to parse a substring:

Given a JSON like:

{
   "Parent" : {
     "SpaceShip":"Tardis",
     "Mark":40
   }
}

And my code is something like:

data class SomeClass(
   @SerialName("SpaceShip") ship:String,
   @SerialName("Mark") mark:Int)

Obviously, Json.nonstrict.parse(SomeClass.serializer(), rawString) will fail because the pair "SpaceShip" and "Mark" are not in the root of the JSON.

How do I make the serializer refer to a subtree of the JSON?

P.S: Would you recommend retrofit instead (because it's older, and maybe more mature)?


Solution

  • import kotlinx.serialization.*
    import kotlinx.serialization.json.Json
    
    
    @Serializable
    data class Parent(
        @SerialName("Parent")
        val parent: SomeClass
    )
    
    @Serializable
    data class SomeClass(
        @SerialName("SpaceShip")
        val ship:String,
        @SerialName("Mark")
        val mark:Int
    )
    
    fun main() {
        val parent = Json.parse(Parent.serializer(), "{\"Parent\":{\"SpaceShip\":\"Tardis\",\"Mark\":40}}")
        println(parent)
    }