2

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

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Maneki Neko
  • 1,177
  • 1
  • 14
  • 24

2 Answers2

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
}
Psijic
  • 743
  • 7
  • 20
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)
}
Markus
  • 46
  • 3
  • 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?... – Maneki Neko May 12 '19 at 15:43