I have the following JSON snippet:
{
"hd":{
"hdEnabled":true,
"defaultStreamQualitySetting":"HD720",
"streamQualitySettings":{
"SD":"SD - low quality",
"HD720":"Standard HD - 720p",
"HD1080":"Full HD - 1080p"
}
}
}
I want to parse the streamQualitySettings with Klaxon and Gson to an object called 'Option' that has a key & description so that I end of with a list of 3 options
How can I achieve this with Klaxon (or Gson)?
This is my code
val jsonArray = bootstrapJsonObject()
.lookup<JsonArray<JsonObject>>("hd.streamQualitySettings")
.first()
val gson = Gson()
val options = ArrayList<Option>()
jsonArray.forEach {
options.add(gson.fromJson(it.toJsonString(), Option::class.java))
}
Why are you using both gson and klaxon? If you want to use gson, then kotson is an alternative with a fluent kotlin dsl.
Here is a solution with klaxon:
fun convert(input: String): List<Option> {
val streamObj = (Parser.default().parse(StringBuilder(input)) as JsonObject)
.obj("hd")!!
.obj("streamQualitySettings")!!
return streamObj.keys.map { Option(it, streamObj.string(it)!!) }
}
Parse, then move down to the streamQualitySettings
.
Get all the keys and map them to Option
.