问题
I'm writing a JSON-style query engine in Java, and it would benefit from the ability to query a JSON document by the DOM path (like you can do in Javascript). I've checked out GSON and Jackson, but neither seem to support this.
Anyone know of any alternatives, or other suggestions rather than rolling my own?
e.g.
//Example JSON document
String json = "{ somewhere : {deep : { inside : 123 } }, anarray : [{val=1}] }";
JsonElement root = JsonParser.parse(json);
//What I'd like:
JsonElement node = root.getByDOM("somewhere.deep"); // {inside : 123}
JsonElement node2 = root.getByDOM("somewhere.deep.inside"); // 123
JsonElement node3 = root.getByDOM("anarray[0].val"); // 1
//etc
回答1:
Jackson most definitely supports this (see "Jackson in 5 minutes", look for "Tree mode") for example:
JsonNode root = mapper.readTree(jsonSource);
and I thought GSON had something similar as well.
But whatever you do, don't try converting JSON to XML, then using XML tools -- that's a path that generally brings you lots of trouble, above and beyond just being slow. This because JSON and XML data models are fundamentally incompatible.
回答2:
Gone with json-path - thanks to brian for the suggestion.
来源:https://stackoverflow.com/questions/13796045/java-json-library-that-supports-dom-style-access