3

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

3 Answers 3

2
@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
}
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

Yup, I haven't found a nicer silver bullet. Something that will look exactly like the JSON and describe it nicely. This is, probably, as good as it gets. And then, the question that rings in my mind: Maybe all the comments are right, and simply GSON is just as good?...
1

A solution if parsing different sets of nested data

import kotlinx.serialization.json.Json
import kotlinx.serialization.Serializable

@Serializable
open class topLevel<T>(val a: Int? = null, val b: T? = null)

@Serializable
open class embadedData1(var s: String? = null)

@Serializable
open class variation1() : topLevel<embadedData1>()

fun main() {

    println( Json.decodeFromString( variation1.serializer(),"""{ "a": 1, "b": { "s": "2" } }""").b?.s )
}

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.