1

One of my Kotlin methods receives a json string similar to the following one:

{
    "12": {
        "1": {
            "a": "0",
            "b": "100",
            "c": "8",
            "d": ""
        },
        "5": {
            "a": "0",
            "b": "100",
            "c": "8",
            "d": ""
        }
    }
    "53": {
        "1": {
            "a": "0",
            "b": "100",
            "c": "8",
            "d": ""
        },
        "5": {
            "a": "0",
            "b": "100",
            "c": "8",
            "d": ""
        }
    }
}

What's the best way to iterate this json? I don't think mapping it into a data object would be the best solution, since it looks like an associative array.

Any hints on that? How can I iterate it like an array?

abierto
  • 1,447
  • 7
  • 29
  • 57
  • 1
    Possible duplicate of [How to parse JSON in Kotlin?](https://stackoverflow.com/questions/41928803/how-to-parse-json-in-kotlin) – Suraj Rao Aug 22 '17 at 07:05
  • If you fully read my question, I'm writing that mapping it into a data class IS NOT the best solution. – abierto Aug 22 '17 at 07:06
  • Why do you say that? Manually parsing JSON sounds like a much worse idea than using a JSON parser. – Matt Aug 22 '17 at 07:23
  • How can I map unexpected strings like "12" or "53" to an object? or "1" and "5" for the second level? Those haven't always the same label as the "a" "b" "c" "d" ones on the last level. If you have any concrete solution please tell me, since probably I'm not understanding what are you meaning. – abierto Aug 22 '17 at 07:27
  • You don't parse the JSON string to a custom class, you parse it to a JSON object. Then you can retrieve the different values like `String value = jsonObject.get("key")`. The exact mechanism will depend on the JSON library you use, but the point is, use a JSON library. Someone else has done all the hard work of parsing JSON, you can just use the library and work with your JSON object. – Matt Aug 22 '17 at 07:31
  • If your data structure is that unpredictable, maybe JSON is not the correct format you should use for this use case? – Piwo Aug 22 '17 at 07:35
  • I've tried with a JSON library, will post a solution. Thanks Matt. – abierto Aug 22 '17 at 08:02

1 Answers1

0

I've found a solution mapping that JSON to a generic structure of Maps, as follows:

import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue

...

val JSON = jacksonObjectMapper()
val test: Map<String, Map<String, Map<String,String>>> = JSON.readValue(jsonString)
abierto
  • 1,447
  • 7
  • 29
  • 57