2

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

  • Option(key = SD, description = "SD - low quality")
  • Option(key = HD720, description = "Standard HD - 720p")
  • Option(key = HD1080, description = "Full HD - 1080p")

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))
}
Robby Smet
  • 4,649
  • 8
  • 61
  • 104

1 Answers1

1

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.

avolkmann
  • 2,962
  • 2
  • 19
  • 27