Java JSON library that supports DOM-style access

霸气de小男生 提交于 2019-12-24 03:27:55

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!