Converting JSON to/from Java Objects using JACKSON API

This post explains Jackson data-binding, which is a common approach when dealing with JSON using Jackson API in your Java projects. Let’s get going.


ObjectMapper is the main api used for data-binding. It comes with several reader/writer methods to preform the conversion from/to Java and JSON

Typical usages are as follows:

//Read JSON and populate java objects
ObjectMapper mapper = new ObjectMapper();
Object value = mapper.readValue(JSON-SOURCE , DESTINATION-JAVA-OBJECT-TYPE);
//JSON-SOURCE can be File/InputStream/String/etc..

//Write JSON from java objects
ObjectMapper mapper = new ObjectMapper();
Object value = mapper.writeValue(JSON-DESTINATION, SOURCE-JAVA-OBJECT);
//JSON-DESTINATION can be File/InputStream/String/etc..

Complete Example

Step 1: Include JACKSON dependency in pom.xml

There are several jar in JACKSON library. For this example, we are only using databind.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.websystique.xml</groupId>
  <artifactId>JsonJacksonObjectMappingExample</artifactId>
  <version>1.0.0</version>
  <packaging>jar</packaging>

  <name>JsonJacksonObjectMappingExample</name>

  <dependencies>
	<dependency>
		<groupId>com.fasterxml.jackson.core</groupId>
		<artifactId>jackson-databind</artifactId>
		<version>2.5.3</version>
	</dependency>
  </dependencies>
 </project>

Step 2: Create POJO’s

These object will be converted to and from JSON.

package com.websystique.json.jackson.model;

import java.util.ArrayList;
import java.util.List;


public class Car {
	
	private String name;
	private String model;
	private long cost;
	private List<String> colors = new ArrayList<String>();
	private CarEngine engine = new CarEngine();
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getModel() {
		return model;
	}
	public void setModel(String model) {
		this.model = model;
	}
	public long getCost() {
		return cost;
	}
	public void setCost(long cost) {
		this.cost = cost;
	}

	public CarEngine getEngine() {
		return engine;
	}
	public void setEngine(CarEngine engine) {
		this.engine = engine;
	}
	
	public List<String> getColors() {
		return colors;
	}
	public void setColors(List<String> colors) {
		this.colors = colors;
	}
	@Override
	public String toString() {
		return "Car [name=" + name + ", model=" + model + ", cost=" + cost
				+ ", colors=" + colors + ", engine=" + engine + "]";
	}
	
	
}

package com.websystique.json.jackson.model;

public class CarEngine {

	private String type;
	private String power;
	public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}
	public String getPower() {
		return power;
	}
	public void setPower(String power) {
		this.power = power;
	}
	
	@Override
	public String toString() {
		return "CarEngine [type=" + type + ", power=" + power + "]";
	}
	
}
package com.websystique.json.jackson.model;

import java.util.ArrayList;
import java.util.List;

public class CarFleet {

	private List<Car> cars = new ArrayList<Car>();


	public List<Car> getCars() {
		return cars;
	}

	public void setCars(List<Car> cars) {
		this.cars = cars;
	}


	@Override
	public String toString() {
		return "CarFleet [cars=" + cars + "]";
	}
}

Step 3: Convert Java Object to JSON and write JSON to a file

Convert CarFleet object into JSON and write that JSON to a file

package com.websystique.json.jackson;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.websystique.json.jackson.model.Car;
import com.websystique.json.jackson.model.CarEngine;
import com.websystique.json.jackson.model.CarFleet;

public class JsonJacksonObjectMappingDemo {

	public static void main(String args[]){
		
		CarFleet carFleet = getCarFleet();
		
		ObjectMapper mapper = new ObjectMapper();

		/**
		 * Write object to file
		 */
		try {
			mapper.writeValue(new File("result.json"), carFleet);//Plain JSON
			//mapper.writerWithDefaultPrettyPrinter().writeValue(new File("result.json"), carFleet);//Prettified JSON
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
	
	private static CarFleet getCarFleet(){
		Car car1 = new Car();
		car1.setName("Audi");
		car1.setModel("2010");
		car1.setCost(30000);
		

		CarEngine engine1 = new CarEngine();
		engine1.setPower("88KWH");
		engine1.setType("Diesel");
		car1.setEngine(engine1);
		
		Car car2 = new Car();
		car2.setName("Jaguar");
		car2.setModel("2013");
		car2.setCost(60000);

		CarEngine engine2 = new CarEngine();
		engine2.setPower("120KWH");
		engine2.setType("Diesel");
		car2.setEngine(engine2);
		
		List<String> colors = new ArrayList<String>();
		colors.add("Grey");
		colors.add("white");
		car1.setColors(colors);
		car2.setColors(colors);
		
		CarFleet carFleet = new CarFleet();
		carFleet.getCars().add(car1);
		carFleet.getCars().add(car2);

		return carFleet;
	}
}

Run above program. Following is the output written in file result.json

{"cars":[{"name":"Audi","model":"2010","cost":30000,"colors":["Grey","white"],"engine":{"type":"Diesel","power":"88KWH"}},{"name":"Jaguar","model":"2013","cost":60000,"colors":["Grey","white"],"engine":{"type":"Diesel","power":"120KWH"}}]}

Pretty print JSON

Note that above output is not very readable. But you can Pretty Print JSON using writerWithDefaultPrettyPrinter factory method of ObjectMapper. Toggle the comments in above program and run it.

{
  "cars" : [ {
    "name" : "Audi",
    "model" : "2010",
    "cost" : 30000,
    "colors" : [ "Grey", "white" ],
    "engine" : {
      "type" : "Diesel",
      "power" : "88KWH"
    }
  }, {
    "name" : "Jaguar",
    "model" : "2013",
    "cost" : 60000,
    "colors" : [ "Grey", "white" ],
    "engine" : {
      "type" : "Diesel",
      "power" : "120KWH"
    }
  } ]
}

Pretty. Isn’t it?

Step 4: Read JSON from a file and convert into Java Object

Read JSON string from a file and convert into CarFleet object.

package com.websystique.json.jackson;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.websystique.json.jackson.model.Car;
import com.websystique.json.jackson.model.CarEngine;
import com.websystique.json.jackson.model.CarFleet;

public class JsonJacksonObjectMappingDemo {

	public static void main(String args[]){
		
		ObjectMapper mapper = new ObjectMapper();

		/**
		 * Read object from file
		 */
		CarFleet value = null;
		try {
			value = mapper.readValue(new File("result.json"), CarFleet.class);
		} catch (Exception e) {
			e.printStackTrace();
		}	
		
		System.out.println(value);
		
	}
	
}

Following is the output:

CarFleet [cars=[Car [name=Audi, model=2010, cost=30000, colors=[Grey, white], engine=CarEngine [type=Diesel, power=88KWH]], Car [name=Jaguar, model=2013, cost=60000, colors=[Grey, white], engine=CarEngine [type=Diesel, power=120KWH]]]]

That’s it. In the next post we will learn how Json can be mapped to Java Maps.

References