2

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
Vadzim
  • 24,954
  • 11
  • 143
  • 151
steve cook
  • 3,116
  • 3
  • 30
  • 51

2 Answers2

0

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.

StaxMan
  • 113,358
  • 34
  • 211
  • 239
  • jackson allows you to read in the tree, but then to get a specific node out you still need to do something like: root.get("somewhere").get("deep") so you end up having to build parser that has to iterate through different levels in order to find the specific node that you want. GSON has the same restriction. – steve cook Dec 11 '12 at 05:53
  • Jackson `JsonNode` has a few find methods (`findValue` etc), if you just need to match a name. And building your own functionality is pretty easy. – StaxMan Dec 12 '12 at 06:13
0

Gone with json-path - thanks to brian for the suggestion.

steve cook
  • 3,116
  • 3
  • 30
  • 51