Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)?

like image 549
Maneki Neko Avatar asked Jul 17 '26 03:07

Maneki Neko


1 Answers

@Serializable
data class Parent(
    @SerialName("Parent")
    val someClass: SomeClass
)

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

fun getSomeClass(inputStream: InputStream): SomeClass {
    val json = Json(JsonConfiguration.Stable)
    val jsonString = Scanner(inputStream).useDelimiter("\\A").next()
    val parent = json.parse(Parent.serializer(), jsonString)
    return parent.someClass
}
like image 180
Psijic Avatar answered Jul 20 '26 02:07

Psijic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!