How to use Jackson databind with JSON

As the use and acceptance of JSON increases, the library to work with JSON also developed. One of the most popular and efficient java based libraries to serialize or map java objects to JSON and vice versa is Jackson. In this post, I will explain how to use the Jackson databind with JSON.

JSON & Jackson

Prerequisite

  • Java 1.8
  • jackson-databind.2.9.5

Jackson Maven dependency

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

You can copy it from the maven repository as well.

In this tutorial I will demonstrate the following:

First create three entity classes Order, Customer, and Item, I will be using them throughout the examples.

Order:

public class Order {

	private String extOrderId;
	
	private double orderAmt;
	
	private String orderDate;

	private Item item;
	
	private Customer customer;
	
        public Order() {
		super();
	}
	public Order(String extOrderId, double orderAmt, String orderDate,Item item,Customer customer) {
		super();
		this.extOrderId = extOrderId;
		this.orderAmt = orderAmt;
		this.orderDate = orderDate;
		this.item = item;
		this.customer = customer;
	}

      // Getter and Setter 
}

Customer:

public class Customer {

	private String customerName;
	
	private String mobile; 
	
	private String email;
	
        public Customer() {
		super();
	}

	public Customer(String customerName, String mobile, String email) {
		super();
		this.customerName = customerName;
		this.mobile = mobile;
		this.email = email;
	}

	public String getCustomerName() {
		return customerName;
	}
    // Getter and Setter
}

Item:

public class Item {

	private String itemName;
	
	private String manufacturer;
	
	private double price;
	
	private boolean fragile;
        
        public Item() {
		super();
	}
	public Item(String itemName, String manufacturer, double price, boolean fragile) {
		super();
		this.itemName = itemName;
		this.manufacturer = manufacturer;
		this.price = price;
		this.fragile = fragile;
	}
   // Getter and Setter
}

How to convert a Java object into JSON?

While using JSON with Java there will be a time when we have to share or write an object in the form of JSON. We can write JSON from java object by ourselves self but that would be very time-consuming. There are several libraries available to achieve these things. Let’s see how we can use Jackson data-bind to convert a Java object into JSON.

import com.codersdesks.jsondemo.bean.Customer;
import com.codersdesks.jsondemo.bean.Item;
import com.codersdesks.jsondemo.bean.Order;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class App {

	public static void main(String[] args) throws JsonProcessingException {
		ObjectMapper mapper = new ObjectMapper();
		
		Item item = new Item("Sports shoes", "Adidas", 3999.99, false);
		Customer customer = new Customer("Player 1", "##########", "email@email.net");
		
		Order order = new Order("ORDER001",2000.22,"10-09-2019",item,customer);
		
		String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(order);
		
		System.out.println(json);
	}
}

When you run the above codes snippet it will print JOSN like below.

{
  "extOrderId" : "ORDER001",
  "orderAmt" : 2000.22,
  "orderDate" : "10-09-2019",
  "item" : {
    "itemName" : "Sports shoes",
    "manufacturer" : "Adidas",
    "price" : 3999.99,
    "fragile" : false
  },
  "customer" : {
    "customerName" : "Player 1",
    "mobile" : "##########",
    "email" : "email@email.net"
  }
}

How to parse JSON to Java object?

As discussed earlier we can use the same library to parse a JSON String into a Java object. Observe the below code snippet.

import java.io.IOException;
import com.codersdesks.jsondemo.bean.Order;
import com.fasterxml.jackson.databind.ObjectMapper;

public class App {

	public static void main(String[] args) throws IOException {
		ObjectMapper mapper = new ObjectMapper();
		String json = "{\"extOrderId\":\"ORDER001\",\"orderAmt\":2000.22,\"orderDate\":\"10-09-2019\"}";
		
		Order order = mapper.readValue(json, Order.class);
		System.out.println("order "+ order);
	}
}

After executing the above code snippet the output will be:

order Order [extOrderId=ORDER001, orderAmt=2000.22, orderDate=10-09-2019, 
item=null, customer=null]

How to parse JSON into List?

Till now we have worked with a single Java object, but sometimes we may have to parse JSON into a List. Let see how it can be achieved. Here we have a JSON with multiple orders like below.

[{
	"extOrderId": "ORDER001",
	"orderAmt": 2000.22,
	"orderDate": "10-09-2019",
	"item": {
		"itemName": "Sports shoes",
		"manufacturer": "Adidas",
		"price": 3999.99,
		"fragile": false
	},
	"customer": {
		"customerName": "Player 1",
		"mobile": "##########",
		"email": "email@email.net" 

	}
}, {
	"extOrderId": "ORDER002",
	"orderAmt": 3099.99,
	"orderDate": "05-09-2019",
	"item": {
		"itemName": "Sports shoes",
		"manufacturer": "Adidas",
		"price": 3999.99,
		"fragile": false
	},
	"customer": {
		"customerName": "Player 1",
		"mobile": "##########",
		"email": "email@email.net"
	}
}]
import java.io.IOException;
import java.util.List;
import com.codersdesks.jsondemo.bean.Order;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

public class App {

	public static void main(String[] args) throws IOException {
		ObjectMapper mapper = new ObjectMapper();
		String json = "[{\"extOrderId\":\"ORDER001\",\"orderAmt\":2000.22,\"orderDate\":\"10-09-2019\",\"item\":"
				+ "{\"itemName\":\"Sports shoes\",\"manufacturer\":\"Adidas\",\"price\":3999.99,\"fragile\":false},"
				+ "\"customer\":{\"customerName\":\"Player 1\",\"mobile\":\"##########\",\"email\":\"email@email.net\"}}"
				+ ",{\"extOrderId\":\"ORDER002\",\"orderAmt\":3099.99,\"orderDate\":\"05-09-2019\",\"item\":{\"itemName\":"
				+ "\"Sports shoes\",\"manufacturer\":\"Adidas\",\"price\":3999.99,\"fragile\":false},\"customer\":"
				+ "{\"customerName\":\"Player 1\",\"mobile\":\"##########\",\"email\":\"email@email.net\"}}]";
		
		List<Order> orders = mapper.readValue(json, new TypeReference<List<Order>>() { });
		
		System.out.println(orders);
	}
}

Once you run the above code it will print:

[Order [extOrderId=ORDER001, orderAmt=2000.22, orderDate=10-09-2019,
item=Item [itemName=Sports shoes, manufacturer=Adidas, price=3999.99, fragile=false],
customer=Customer [customerName=Player 1, mobile=##########, email=email@email.net]
],
Order [extOrderId=ORDER002, orderAmt=3099.99, orderDate=05-09-2019,
item=Item [itemName=Sports shoes, manufacturer=Adidas, price=3999.99, fragile=false],
customer=Customer [customerName=Player 1, mobile=##########, email=email@email.net]
]]

How to parse JSON into Map?

Similar to Converting JSON into a Java object or converting JSON into a list we can convert JSON into a Map as well. Observe the below code snippet.

import java.io.IOException;
import java.util.Map;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

public class App {

	public static void main(String[] args) throws IOException {
		ObjectMapper mapper = new ObjectMapper();
		String json = "{\"extOrderId\":\"ORDER001\",\"orderAmt\":2000.22,\"orderDate\":\"10-09-2019\"}";
		
		Map<String, String> map = mapper.readValue(json, new TypeReference<Map<String, String>>() {});
		
		System.out.println(map);
	}
}

Once you run the code snippet it will print:

{extOrderId=ORDER001, orderAmt=2000.22, orderDate=10-09-2019}

How to ignore object property?

Enough of parsing JSON into an object and converting an object into JSON. Apart from this requirement while working on a real-world application sometimes you may face a situation where you have an existing class, which needs to be converted into JSON, but you have to omit some properties while writing the JSON.

For example, you have a User class like below, where you have to share the details of a user in the form JSON. But the User class also has a property password that holds the password of the user. In any case, you don’t want to share the user details with a password. In such cases, you can use @JsonIgnore annotation provided by Jackson data bind.

import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonIgnore;

public class User implements Serializable{

	private static final long serialVersionUID = -1686914925084201531L;

	private int id;
	private String name;
	private String email;
	
	@JsonIgnore
	private String password;
	
	public User() {
		super();
	}
	
	public User(int id, String name, String email, String password) {
		super();
		this.id = id;
		this.name = name;
		this.email = email;
		this.password = password;
	}
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + ", email=" + email + ", password=" + password + "]";
	}
	
}

Let’s create an object of User class and write it as JSON. Observer the following code snippet with its output.

import java.io.IOException;
import com.codersdesks.jsondemo.bean.User;
import com.fasterxml.jackson.databind.ObjectMapper;

public class App {

	public static void main(String[] args) throws IOException {
		ObjectMapper mapper = new ObjectMapper();
		User user = new User(1, "User 1", "user1@email.net", "password");
		System.out.println(mapper.writeValueAsString(user));
	}
}

When you run the above code snippet it will print the JSON of the User as below after omitting the password property in JSON.

{"id":1,"name":"User 1","email":"user1@email.net"}

Recommended Read:

What is JavaScript Object Notation (JOSN)

Happy Learning !!

Leave a Comment