Skip to content

Instantly share code, notes, and snippets.

@kassim
Last active November 17, 2022 00:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kassim/4e0acaef654749d888bee177b71f375d to your computer and use it in GitHub Desktop.
Save kassim/4e0acaef654749d888bee177b71f375d to your computer and use it in GitHub Desktop.
Kotlin Extensions for old versions of org.json.JSONObject and JSONArray that provide toMap and toList functions
import org.json.JSONArray
import org.json.JSONObject
fun JSONObject.toMap(): Map<String, Any?> =
keys().asSequence().associateWith { key -> toValue(get(key)) }
fun JSONArray.toList(): List<Any?> =
(0 until length()).map { index -> toValue(get(index)) }
private fun toValue(element: Any) = when (element) {
JSONObject.NULL -> null
is JSONObject -> element.toMap()
is JSONArray -> element.toList()
else -> element
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment