Skip to content

Instantly share code, notes, and snippets.

@alexmelyon
Created December 4, 2018 14:11
Show Gist options
  • Save alexmelyon/c71875fd4bc141952876e599e713f956 to your computer and use it in GitHub Desktop.
Save alexmelyon/c71875fd4bc141952876e599e713f956 to your computer and use it in GitHub Desktop.
import com.google.gson.JsonObject
fun main(args: Array<String>) {
val json = JsonObject()
json.commit {
addProperty("added_property", "This is the added property")
}
json.commit {
remove("added_property")
}
json.commit {
addProperty("name", "The name")
}
json.commit {
addProperty("name", "The NEW name")
}
}
fun JsonObject.commit(block: JsonObject.() -> Unit) {
val before = xpathToValue(this).map { it.first + ": " + it.second }.toMutableList()
block()
val after = xpathToValue(this).map { it.first + ": " + it.second }.toMutableList()
(before + after).forEach {
if (before.contains(it) && after.contains(it)) {
before.remove(it)
after.remove(it)
}
}
before.forEach { println("- $it") }
after.forEach { println("+ $it") }
}
fun xpathToValue(json: JsonObject): List<Pair<String, String>> {
return json.entrySet().flatMap { nameToObj ->
if (nameToObj.value.isJsonObject) {
xpathToValue(nameToObj.value.asJsonObject).map { "${nameToObj.key}/${it.first}" to it.second }
} else if (nameToObj.value.isJsonArray) {
val res = nameToObj.value.asJsonArray
.mapIndexed { i, value -> i to value }
.fold(JsonObject()) { total, next -> total.apply { add("${nameToObj.key}/${next.first}", next.second) } }
xpathToValue(res)
} else {
listOf(nameToObj.key to nameToObj.value.asJsonPrimitive.toString())
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment