Posted In: Jackson 2X, JSON

Generate Java POJO from JSON or JSON schema – Annotation style – Jackson 2.x

 

We created POJOs from JSON in previous example generate-java-pojo-from-json-or-json-schema. Let us go through some options that we have on http://www.jsonschema2pojo.org/


 

Annotation style – Jackson 2.x

This will add annotations like @JsonProperty, @JsonPropertyOrder, @JsonInclude to your POJOs. Jackson will use these annotations for mapping fields to JSON. It has side effect and cause production down situation. Side effect is if you do not add @JsonIgnoreProperties to this class any additional properties added to JSON will cause Jackson Object Mapping to fail.
Following code will generate following exception due to new field “city”
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field
 

package com.example;

import java.io.Reader;
import java.io.StringReader;

import com.fasterxml.jackson.databind.ObjectMapper;

public class Main2 {
	public static void main(String a[]) {
		ObjectMapper objectMapper = new ObjectMapper();
		String json = "{" + "\"addresses\": [" + "{"
		        + " \"addressID\": \"90ace06b-2257-4760-9dec-75a4ca679d0e\","
		        + " \"flatNumber\": \"102\","
		        + "  \"city\": \"city\"" + "}," + "{"
		        + "  \"addressID\": \"90ace06b-2257-4760-9dec-75a4ca679d0e\","
		        + "  \"flatNumber\": \"102\","
		        + "  \"city\": \"city\"" + "}" + "]" + "}";
		try {
			Reader reader = new StringReader(json);
			Addresses addresses = objectMapper.readValue(reader,
			        Addresses.class);
			System.out.println(addresses);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

 

Add JsonIgnoreProperties annotation to POJO to resolve UnrecognizedPropertyException
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown=true)
public class Address {
.......
Advantage of using these Jackson annotations like @JsonProperty is you could change JSON key to different POJO field. For example you could do following
@JsonProperty("flatNumber")
public String getFlatNumberNew() {
	return flatNumberNew;
}
@JsonProperty("flatNumber")
public void setFlatNumberNew(String flatNumberNew) {
	this.flatNumberNew = flatNumberNew;
}

 
 

Tags: , , , , , ,

by , on February 20th, 2017

  • Categories