Skip to content

Instantly share code, notes, and snippets.

@s4cha
Last active October 19, 2018 17:43
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 s4cha/35ce13e27c9e91bce2de4b32313102da to your computer and use it in GitHub Desktop.
Save s4cha/35ce13e27c9e91bce2de4b32313102da to your computer and use it in GitHub Desktop.
Kotlin JSON parsing \o/
// Usage
fun parse(json: JSONObject): Car {
val car = Car()
car.apply {
::id < json.key("id")
::numberOfDoors < json.key("nb_of_doors")
::driverName < json.key("driver_name")
}
return car
}
// JSON Kotlin Magick
fun JSONObject.key(key:String): Pair<JSONObject, String> = Pair(this, key)
inline operator fun <reified T>KMutableProperty0<T>.compareTo(pair: Pair<JSONObject, String>): Int {
pair.first.map(this, pair.second)
return 0
}
inline fun <reified T>JSONObject.map(property: KMutableProperty0<T>, key: String) {
if (has(key)) {
when (T::class) {
String::class -> (property as? KMutableProperty0<String>)?.apply { set(getString(key)) }
Long::class -> (property as? KMutableProperty0<Long>)?.apply { set(getLong(key)) }
Double::class -> (property as? KMutableProperty0<Double>)?.apply { set(getDouble(key)) }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment