How to Map JSON to Java Object by Annotation?


Jackson provide annotation for mapping Java and JSON properties that help when mapping fields in JSON and Java objects are having different names and some properties are additional and not match.

Pre-Requisite 

Add below jackson-databind-2.8.5.jar in your classpath or make dependency entry in pom.xml file.

  <dependency>
	<groupId>com.fasterxml.jackson.core</groupId>
	<artifactId>jackson-databind</artifactId>
	<version>2.8.5</version>
  </dependency>
 

Example

In below example showing to map Student object from JSON to Java  where field name id is in JSON while rollNumber is Java object and JAVA object also having additional field which is not mapped with any fields for this we have to use @JsonIgnoreProperties(ignoreUnknown = true) on class level to ignore this field or if some more.

Annotation Used

Ignore Unknown Properties
@JsonIgnoreProperties(ignoreUnknown = true)
JSON to Java properties match
@JsonProperty(value = "XYZ")

JSON Sample Data

Add below JSON data in student_data.txt file to execute this program.

[
{
  "id" : 11,
  "firstName" : "Saurabh",
  "lastName" : "Gupta",
  "permanent" : false,
  "address" : {
    "addressLine" : "Lake Union Hill Way",
    "city" : "Atlanta",
    "state" : "GA",
    "zipCode" : 50005
  },
  "phoneNumbers" : [ 2233445566, 3344556677 ],
  "cities" : [ "Dallas", "San Antonio", "Irving" ],
  "properties" : {
    "play" : "Badminton",
    "interst" : "Math",
    "age" : "34 years"
  }
},
{
  "id" : 12,
  "firstName" : "Gaurav",
  "lastName" : "Khaira",
  "permanent" : true,
  "address" : {
    "addressLine" : " 5770 Shiloh woods dr",
    "city" : "Cumming",
    "state" : "GA",
    "zipCode" : 50007
  },
  "phoneNumbers" : [ 2233445567, 3344556678 ],
  "cities" : [ "New York", "Austin", "Plano" ],
  "properties" : {
    "play" : "Baseball",
    "interst" : "Science",
    "age" : "36 years"
  }
}
]

Example

package test.facingissesonit.json.jacson;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;

import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class ConvertJsonToArrayList {

	public static void main(String[] args) {
		try
		{
		byte[] mapData = Files.readAllBytes(Paths.get("student_data.txt"));
		Student[] studentArr = null;

		ObjectMapper objectMapper = new ObjectMapper();
		studentArr = objectMapper.readValue(mapData, Student[].class);
		List<Student> studentList=Arrays.asList(studentArr);
		System.out.println("Student 1 \n"+studentList.get(0));
		System.out.println("Student 2 \n"+studentList.get(1));

		}
		catch(JsonMappingException ex)
		{
			ex.printStackTrace();
		}
		catch(IOException ex)
		{
			ex.printStackTrace();
		}
	}
}

Model Class

Below Student and Address classes are required to execute this program. Here field rollNumber is mapping with property id and others property too and using @JsonIgnoreProperties(ignoreUnknown = true) for ignoring additional fields which are not mapped.

package test.facingissesonit.json.jacson;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Student {
	@JsonProperty(value = "id")
	private int rollNumber;
	@JsonProperty(value = "firstName")
	private String firstName;
	@JsonProperty(value = "lastName")
	private String lastName;
	@JsonProperty(value = "permanent")
	private boolean permanent;
	@JsonProperty(value = "address")
	private Address address;
	@JsonProperty(value = "phoneNumbers")
	private long[] phoneNumbers;
	@JsonProperty(value = "cities")
	private List<String> cities;
	@JsonProperty(value = "properties")
	private Map<String, String> properties;
	private Date dateOfJoining =new Date();
	@Override
	public String toString()
	{
		StringBuffer sb=new StringBuffer();
		sb.append("==============Student Information================\n");
		sb.append("rollNumber=").append(rollNumber).append("\n");
		sb.append("firstName=").append(firstName).append("\n");
		sb.append("lastName=").append(lastName).append("\n");
		sb.append("permanent=").append(permanent).append("\n");
		sb.append("adress=").append(address).append("\n");
		sb.append("phoneNumbers=").append(Arrays.toString(phoneNumbers)).append("\n");
		sb.append("cities=").append(Arrays.toString(cities.toArray(new String[cities.size()]))).append("\n");
		sb.append("properties=").append(properties).append("\n");
		sb.append("dateOfJoining=").append(dateOfJoining).append("\n");
		return sb.toString();
	}
	public int getRollNumber() {
		return rollNumber;
	}
	public void setRollNumber(int rollNumber) {
		this.rollNumber = rollNumber;
	}
	public String getFirstName() {
		return firstName;
	}
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
	public String getLastName() {
		return lastName;
	}
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	public boolean isPermanent() {
		return permanent;
	}
	public void setPermanent(boolean permanent) {
		this.permanent = permanent;
	}
	public Address getAddress() {
		return address;
	}
	public void setAddress(Address address) {
		this.address = address;
	}
	public long[] getPhoneNumbers() {
		return phoneNumbers;
	}
	public void setPhoneNumbers(long[] phoneNumbers) {
		this.phoneNumbers = phoneNumbers;
	}
	public List<String> getCities() {
		return cities;
	}
	public void setCities(List<String> cities) {
		this.cities = cities;
	}
	public Map<String, String> getProperties() {
		return properties;
	}
	public void setProperties(Map<String, String> properties) {
		this.properties = properties;
	}
	public Date getDateOfJoining() {
		return dateOfJoining;
	}
	public void setDateOfJoining(Date dateOfJoining) {
		this.dateOfJoining = dateOfJoining;
	}
}

package test.facingissesonit.json.jacson;

import com.fasterxml.jackson.annotation.JsonProperty;

public class Address {
@JsonProperty(value = "addressLine")
private String addressLine;
@JsonProperty(value = "city")
private String city;
@JsonProperty(value = "state")
private String state;
@JsonProperty(value = "zipCode")
private int zipCode;
@Override
public String toString()
{
	StringBuffer sb=new StringBuffer();
	sb.append("AddressLine=").append(addressLine).append("\n");
	sb.append("city=").append(city).append("\n");
	sb.append("state=").append(state).append("\n");
	sb.append("zipCode=").append(zipCode).append("\n");
	return sb.toString();
}
public String getAddressLine() {
	return addressLine;
}
public void setAddressLine(String addressLine) {
	this.addressLine = addressLine;
}
public String getCity() {
	return city;
}
public void setCity(String city) {
	this.city = city;
}
public String getState() {
	return state;
}
public void setState(String state) {
	this.state = state;
}
public int getZipCode() {
	return zipCode;
}
public void setZipCode(int zipCode) {
	this.zipCode = zipCode;
}
}

Output

Student 1
==============Student Information================
rollNumber=11
firstName=Saurabh
lastName=Gupta
permanent=false
adress=AddressLine=Lake Union Hill Way
city=Atlanta
state=GA
zipCode=50005

phoneNumbers=[2233445566, 3344556677]
cities=[Dallas, San Antonio, Irving]
properties={play=Badminton, interst=Math, age=34 years}
dateOfJoining=Sat May 20 22:41:52 EDT 2017

Student 2
==============Student Information================
rollNumber=12
firstName=Gaurav
lastName=Khaira
permanent=true
adress=AddressLine= 5770 Shiloh woods dr
city=Cumming
state=GA
zipCode=50007

phoneNumbers=[2233445567, 3344556678]
cities=[New York, Austin, Plano]
properties={play=Baseball, interst=Science, age=36 years}
dateOfJoining=Sat May 20 22:41:52 EDT 2017

More Sample Code

For more java and JDBC codes follow below links

About Saurabh Gupta

My Name is Saurabh Gupta, I have approx. 10 Year of experience in Information Technology World manly in Java/J2EE. During this time I have worked with multiple organization with different client, so many technology, frameworks etc.
This entry was posted in Java, JSON and tagged . Bookmark the permalink.