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)?
@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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With