Monday, October 11, 2010

Jackson tips: overriding serializer or type for Map keys, values, Collection/List values

I have only recently realized that much of Jackson functionality is a unknown to most users. Part of unawareness is due to lack of documentation; but even though documentation has arguably been improving over time (at least Javadocs and rest of FasterXML wiki), there are limits to what can be achieved by feature-listing style of documentation. To add supporting documentation, then, I am trying to write bit more about both specific features that could use more spotlight, as well as more how-to style explanations.

So let's start with something reasonably simple that is not universally known by Jackson users (this is actually based on my answer to one expert user):

Jackson Tip of 21-Oct-2010: annotations for overriding deserialization settings of Collection and Map properties

Let's say that you have bean like this:

class Bean {
  public List<Object> values;

where you want to deserialize List entries as type 'ValueBean'. To specify type of 'values' property itself you could use annotation; but this can not be used to define content type (since annotation values can not be generic types, only classes). So how do you do specify deserialization type of List values (or Map values)? One possibility would be specifying a custom deserializer, but that would be an overkill.

It is actually simple enough: there is another @JsonDeserialize property to use for this use case:

class Bean {
  public List<Object> values;

which also works for Map values (for Map keys you would use @JsonDeserialize.keyAs).

Similarly, you can explicitly specify deserializer to use for keys and values using @JsonDeserialize.contentUsing and @JsonDeserialize.keyUsing instead of basic @JsonDeserialize.using which is used for the property itself:

class Bean {
  public List<Object> values;

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.