I'm trying to convert a nested Map to a JSONObject like so:
fun convertToJson(input: Map<String, Any>): JSONObject {
val jsonObject = JSONObject()
input.forEach { (key, value) ->
if (value is Map<*, *>) {
val iterator = value.entries.iterator()
while (iterator.hasNext()) {
val pairs = iterator.next()
(pairs.key as? String)?.let { k ->
pairs.value?.let { v ->
jsonObject.put(k, v)
}
}
}
}
jsonObject.put(key, value)
}
return jsonObject
}
(I tried following this example Putting HashMap<String, object> in jsonobject)
I call it like so
val input = mapOf(
"key1" to mapOf("inner_key1" to "foo"))
val output = convertToJson(input)
What I don't understand, is why is
output.optJSONObject("key1")
null?
From what I understand, output.opt("key1")
returns a Map<*, *>
.
That's about as far as I got. I'm not sure if my convertToJson
needs fixing, or if my understanding needs correcting, in that, optJSONObject
should not be used for nested types and I should use opt
if I know the type will be a Map
.