Saturday, September 18, 2010

Jackson 1.6, improved Tree Model access; finding values of all instances of specified property

One class of improvements included in Jackson 1.6 are improvements to Tree Model accessors, added to JsonNode.

So, for example, if you have an array of User objects:

  { "name" : "Billy", "id" : 123 },
  { "name" : "Bob", "id" : 456, "extraInfo" : { "flags" : 3 } } // and so on   

and you would just like to get list of names of all users, formerly you needed to write piece of glue code to get names, build a List and so on. While simple to do, it is boring and ultimately error-prone thing to have to do.

So new functionality that was added can simplify such tasks:

  JsonNode root = objectMapper.readTree(json);
  List<JsonNode> nameNodes = root.findValues("name");
  // or, given we know they are Strings, we can get actual name values directly:
  List<string> nameStrings = root.findValuesAsText("name");

Or, if you actually wanted to just find Users that have property "extraInfo" defined, you would do:

  List<JsonNode> nodes = root.findParents("extraInfo");

Granted, these find methods are not superbly powerful -- hopefully we can work on actual JSON path expressions in future -- but they help a bit for common cases.
And even without formal expression language, perhaps we could add filter-based alternatives for more concise recursive-descent lookups (findValues(new NodeFilter() { .... } ) ?)

blog comments powered by Disqus

Sponsored By

Related Blogs

(by Author (topics))

Powered By

About me

  • I am known as Cowtowncoder
  • Contact me
Check my profile to learn more.