Last active
November 17, 2022 00:46
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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