Java Jackson – Json annotations and dyna beans

Also see json simple org.json

The json string at times have a lot of properties. It seems a waste creating a POJO with all those properties. Wouldnt it be great if there was a catch’all that could read all properties in a map? Jackson provides annotations to do just that. In the example below we have set two properties in the bean and the other properties are read into a map. These example also introduces some common annotations using in Jackson. Lets look at them briefly:

  1. @JsonProperty-This annotation is used to mark a method as a getter or setter for a property. In other words, it associates a json field with a java property. If a name is specified (@JsonProperty(“age”)) then the java property that is annotated with this annotation is mapped to the ‘age’ field of the json, If no name is specified the java property name is used.
  2. @JsonCreator-This annotation is used the define constructors that are used to create java objects from json string. It is used during data binding and specifies properties that will be used to create java objects during deserialization.
  3. @JsonAnyGetter and @JsonAnySetter – This annotations are used to mark methods that set or read fields that are not handled by any other java property. These act like catch-all and handle all fields that are not handled by any other java property. The fields are stored in a map as key value pairs.

Data Binding Example

Databinding

The Albums class

Dataset class

Leave a Reply

Your email address will not be published. Required fields are marked *