klaxon
klaxon copied to clipboard
Finding a nested object when we don't know the full path
How can we return a nested object?
Let's say I have
{ "a": { "b": { "c": 1 } } }
How do I retrieve "c"
?
JsonBase.lookup(…)
receives only full paths so if I don't know the full path to "c"
I cannot use this.
On the other hand, PathMatcher
cannot return anything since it has a method onMatch(…)
that happens in the background and you cannot return anything from this method.
Indeed the lack of a return value when using path matcher is confusing. Naively users may expect it to behave similarly to FileFilter from java sdk to match and filter the parsed DOM, but it does not do so. In fact the return value of
val parsed = Klaxon().pathMatcher(object : PathMatcher {
override fun pathMatches(path: String) = Pattern.matches(".*Snapshots.*SnapshotRaw.Containers.*", path)
override fun onMatch(path: String, value: Any) {
println(value)}
}).parseJsonObject(StringReader(endPointsJson!!))
seems to be always the same no matter what path is used.
What for sure works is (((parsed["Snapshots"] as JsonArray<*>)[0] as JsonObject)["SnapshotRaw"] as JsonObject)["Containers"]
but this lacks beauty so some path like query would be really helpful here.
Also parsed.array<Any>("Snapshots[0].SnapshotRaw.Containers")
does not seem be applicable here.