Friday, January 16, 2009

More Action, Jackson! (0.9.6) Thaw Me Objects!

So here's another Jackson release, this time version 0.9.6. Although the version difference is miniscule (just patch level increase -- we are running out of pre-1.0 version numbers here!), this is another rather significant upgrade. Why? Because now the Number One feature request -- Full Bean/POJO de-serialization (read Java objects from Json) -- is finally implemented.

So how do I do it? It is actually rather simple in most cases: try this:

  MyBean bean = new ObjectMapper().readValue(jsonFile, MyBean.class);
  // maybe something that you earlier wrote using "mapper.writeValue(bean, 

The only requirement is that MyBean has suitable access methods:

  • Getters (String getName() etc) are needed to serialize (write Objects as Json)
  • Setters (setName(String)) are needed to deserialize (read Objects from Json)
  • for deserialization, a no-arg default constructor is also needed

In future there may be additional serialization mechanisms (perhaps field-based introspection; and certainly annotations to rename properties and indicate methods with less regular names), but for now above will (have to) suffice.

In addition to handling beans well, support for Generics containers works as expected: the only caveats are that:

  • For properties of beans, full Generic type must be included in the set method for deserialization (not needed for serialization)
  • For root-level object type, basic class is not enough (do not try 'List l = mapper.readValue(src, List.class);', won't work): instead you must do: 'List<String> l = mapper.readValue(src, new TypeReference<List<String>>() { } );'. This complexity is due to Java Type Erasure (see earlier blog entries for more details)

So what else is new with 0.9.6? Packaging for one: Jackson now comes in 2 jars:

  • "Core" contains JsonParser and JsonGenerator APIs, implementations
  • "Mapper" contains 2 mappers: "ObjectMapper" that does data binding mentioned above, and "TreeMapper" that can construct DOM-like trees that consist of JsonNode objects. Latter are convenient for more dynamic (scripting-like) access and traversal.

As usual: if you have already used Jackson, do us all favour and download & use the new version! And if not, well, perhaps download and try out the new version! You will like it.

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.