Hurry! Try our new Interactive Courses for FREE. 🥳   🚀

Jackson ObjectMapper

The Jackson ObjectMapper class is used to map objects to JSON or JSON to objects. It is a simple-to-use class that provides us with a lot of different options to parse JSON.

JSON is a widely used file format used for storing and transferring property-value pairs of classes.

In this tutorial, we will learn more about this class.

Reading Using ObjectMapper in Java

We can read objects from a JSON file, a JSON string or URL, and even a JSON string array using the ObjectMapper class.

We will use the class defined below for this tutorial. Make sure to add the necessary dependencies or the jar files to the classpath before going forward with the tutorial.

class DemoClass
{
    private String field1;
    private Double field2;
    
    //Constructors
    DemoClass()
    {}    
    DemoClass(String field1, Double field2)
    {
    	this.field1 = field1;
    	this.field2 = field2;
    }    
    //getters and setters
	public String getField1() {
		return field1;
	}
	public void setField1(String field1) {
		this.field1 = field1;
	}
	public Double getField2() {
		return field2;
	}
	public void setField2(Double field2) {
		this.field2 = field2;
	}
}

Reading Objects from a JSON File

We can use the readValue() method of this class and read data from a JSON file into an object. Our JSON file contains just a single object's property-value pairs.

import java.io.File;

public class ObjectMapperDemo
{
	public static void main(String[] args)
	{
		try
		{
			//File to read from
			String filePath = "C:\\Users\\Lenovo\\Desktop\\jsonDemo.json";
			File file = new File(filePath);
			
			ObjectMapper objMapper = new ObjectMapper();
			DemoClass obj = new DemoClass();
			obj = objMapper.readValue(file, DemoClass.class);
			
			System.out.print(obj.getField1() + " " + obj.getField2());
		}
		catch(Exception e)
		{
			System.out.print(e);
		}
	}
}


Sample-1 20.21

Reading Objects from a JSON String

We can copy the contents of a JSON file into a Java string and create an object from this string. We will again use the readValue() method of the ObjectMapper class. We also need to pass the class type to this method.

public class ObjectMapperDemo
{
	public static void main(String[] args)
	{
		try
		{
			String jsonString = "{\"field1\":\"Sample-1\",\"field2\":20.21}";
			ObjectMapper objMapper = new ObjectMapper();
			
			DemoClass obj = new DemoClass();
			obj = objMapper.readValue(jsonString, DemoClass.class);
			
			System.out.print(obj.getField1() + " " + obj.getField2());
		}
		catch(Exception e)
		{
			System.out.print(e);
		}
	}
}


Sample-1 20.21

Reading Objects from a JSON URL

Reading objects from a URL is also pretty straightforward. We need to pass the URL object and the class type to the readValue() method.

import java.net.URL;
public class ObjectMapperDemo
{
	public static void main(String[] args)
	{
		try
		{
			ObjectMapper objMapper = new ObjectMapper();
			
			URL jsonFileUrl = new URL("file:C:\\Users\\Lenovo\\Desktop\\jsonDemo.json");
			DemoClass obj = new DemoClass();
			obj = objMapper.readValue(jsonFileUrl, DemoClass.class);
			
			System.out.print(obj.getField1() + " " + obj.getField2());
		}
		catch(Exception e)
		{
			System.out.print(e);
		}
	}
}


Sample-1 20.21

Reading from a JSON String Array to an Object Array

Suppose a string contains multiple objects data(as an array) in JSON format. We can read all this data into an array of the class type using the ObjectMapper class.

public class ObjectMapperDemo
{
	public static void main(String[] args)
	{
		try
		{
			//String with two DemoClass Objects
			String jsonString = "[{\"field1\":\"Sample-1\",\"field2\":20.21}, {\"field1\":\"Sample-2\",\"field2\":22.55}]";
			ObjectMapper objMapper = new ObjectMapper();
			//Reading into an object array
			DemoClass[] objectArr = objMapper.readValue(jsonString, DemoClass[].class);
			//Printing the objects
			for(DemoClass obj : objectArr)
				System.out.println(obj.getField1() + " " + obj.getField2());
		}
		catch(Exception e)
		{
			System.out.print(e);
		}
	}
}


Sample-1 20.21
Sample-2 22.55

Reading from a JSON String Array to an Object List

We can read the objects into a list if we don't want to read data into a fixed-sized object array.

public class ObjectMapperDemo
{
	public static void main(String[] args)
	{
		try
		{
			//String with two DemoClass Objects
			String jsonString = "[{\"field1\":\"Sample-1\",\"field2\":20.21}, {\"field1\":\"Sample-2\",\"field2\":22.55}]";
			ObjectMapper objMapper = new ObjectMapper();
			
			//Reading into an object List
			List<DemoClass> objectList = objMapper.readValue(jsonString, new TypeReference<List<DemoClass>>(){});
			
			//Printing the objects
			for(DemoClass obj : objectList)
				System.out.println(obj.getField1() + " " + obj.getField2());
		}
		catch(Exception e)
		{
			System.out.print(e);
		}
	}
}


Sample-1 20.21
Sample-2 22.55

Reading from a JSON String Array to an Object Map

We can also read data from a JSON string into a Map. Each property of the class will become a key, and the property value will become the value.

public class ObjectMapperDemo
{
	public static void main(String[] args)
	{
		try
		{
			String jsonString = "{\"field1\":\"Sample-1\",\"field2\":20.21}";
			
			ObjectMapper objMapper = new ObjectMapper();
			//Reading into an object Map
			Map<String, Object> objectMap = objMapper.readValue(jsonString, HashMap.class);
			
			for(Map.Entry<String, Object> e : objectMap.entrySet())
				System.out.println(e.getKey() + " " + e.getValue());
		}
		
		catch(Exception e)
		{
			System.out.print(e);
		}
	}
}


field1 Sample-1
field2 20.21

Reading JSON to a JsonNode object

The JsonNode class provides us a more flexible way to parse JSON. We can use the readTree() method of ObjectMapper class to read JSON into a JsonNode object.

public class ObjectMapperDemo
{
	public static void main(String[] args)
	{
		try
		{
			//String with two DemoClass Objects
			String jsonString = "{\"field1\":\"Sample-1\",\"field2\":20.21}";
			ObjectMapper objMapper = new ObjectMapper();
			
			JsonNode node = objMapper.readTree(jsonString);
			String field1 = node.get("field1").asText();
			String field2 = node.get("field2").asText();
			
			System.out.print(field1 + " " + field2);			
		}
		catch(Exception e)
		{
			System.out.print(e);
		}
	}
}


Sample-1 20.21

Writing JSON from Objects

We can write objects into a JSON file using the ObjectMapper class. The writeValue() method of this class is used to serialize and write an object to a JSON file.

import java.io.File;
public class ObjectMapperDemo
{
	public static void main(String[] args)
	{
		DemoClass obj = new DemoClass("Sample-1", 20.21);//object to write		
		try
		{
			//File to write object in
			String filePath = "C:\\Users\\Lenovo\\Desktop\\jsonDemo.json";
			File file = new File(filePath);
			
			ObjectMapper objMapper = new ObjectMapper();
			objMapper.writeValue(file, obj);
		}
		catch(Exception e)
		{
			System.out.print(e);
		}
	}
}

The content of the JSON file is shown below.


{"field1":"Sample-1","field2":20.21}

Serialize an Object to JSON

We can also serialize an object to a JSON string using the writeValueAsString() method.

public class ObjectMapperDemo
{
	public static void main(String[] args)
	{
		DemoClass obj = new DemoClass("Sample-1", 20.21);//object to write		
		try
		{
			ObjectMapper objMapper = new ObjectMapper();
			String jsonString = objMapper.writeValueAsString(obj);//Generating JSON as a String
			System.out.print(jsonString);
		}
		catch(Exception e)
		{
			System.out.print(e);
		}
	}
}


{"field1":"Sample-1","field2":20.21}

Similarly, the writeValueAsBytes() will return a byte array corresponding to an object.

public class ObjectMapperDemo
{
	public static void main(String[] args)
	{
		DemoClass obj = new DemoClass("Sample-1", 20.21);//object to write		
		try
		{
			ObjectMapper objMapper = new ObjectMapper();
			byte[] jsonByteArr = objMapper.writeValueAsBytes(obj);
			String strFromByteArr = new String(jsonByteArr);
			System.out.print(strFromByteArr);
		}
		catch(Exception e)
		{
			System.out.print(e);
		}
	}
}


{"field1":"Sample-1","field2":20.21}

Configuring ObjectMapper

We can configure the ObjectMapper so that it can work with unexpected inputs. For example, reading a JSON string that has some unknown properties will lead to an UnrecognizedPropertyException. This is demonstrated by the code below.

public class ObjectMapperDemo
{
	public static void main(String[] args)
	{
		try
		{
			//String with an unknown field3 property
			String jsonString = "{\"field1\":\"Sample-1\",\"field2\":20.21,\"field3\":\"Unknown\"}";
			ObjectMapper objMapper = new ObjectMapper();
			
			DemoClass obj = new DemoClass();
			obj = objMapper.readValue(jsonString, DemoClass.class);	
		}
		catch(Exception e)
		{
			System.out.print(e);
		}
	}
}

We can configure our ObjectMapper to ignore any new properties. This is done by using the configure() method.

public class ObjectMapperDemo
{
	public static void main(String[] args)
	{
		try
		{
			//String with an unknown field3 property
			String jsonString = "{\"field1\":\"Sample-1\",\"field2\":20.21,\"field3\":\"Unknown\"}";
			ObjectMapper objMapper = new ObjectMapper();
			objMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
			DemoClass obj = new DemoClass();
			obj = objMapper.readValue(jsonString, DemoClass.class);	
			System.out.print(obj.getField1() + " " + obj.getField2());
		}
		catch(Exception e)
		{
			System.out.print(e);
		}
	}
}


Sample-1 20.21

We can also configure ObjectMapper to work with null values for primitive types.

ObjectMapper objMapper = new ObjectMapper();

objMapper .configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false);

Working With Dates

By default, the ObjectMapper will map a java.util.date to a long value. This long value is the number of milliseconds passed since January 1, 1970. This is not a very convenient format.

Let's add a date field to our DemoClass, and serialize an object to JSON.

class DemoClass
{
    private String field1;
    private Double field2;
    private Date dateField;
    
    //Constructors
    DemoClass()
    {}    
    DemoClass(String field1, Double field2, Date d)
    {
    	this.field1 = field1;
    	this.field2 = field2;
    	this.dateField = d;
    }    
    //getters and setters
}
public class ObjectMapperDemo
{
	public static void main(String[] args)
	{
		try
		{
			DemoClass obj = new DemoClass("Sample-1", 20.21, new Date());
			ObjectMapper objMapper = new ObjectMapper();
			
			String jsonString = objMapper.writeValueAsString(obj);
			System.out.print(jsonString);
		}
		catch(Exception e)
		{
			System.out.print(e);
		}
	}
}


{"field1":"Sample-1","field2":20.21,"dateField":1627623983148}

However, we can define a date format using the SimpleDateFormat to serialize the java.util.date.

public class ObjectMapperDemo
{
	public static void main(String[] args)
	{
		try
		{
			ObjectMapper objMapper = new ObjectMapper();
			//Creating and setting a date format
			SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yy");
			objMapper.setDateFormat(dateFormat);
			
			DemoClass obj = new DemoClass("Sample-1", 20.21, new Date());
			String jsonString = objMapper.writeValueAsString(obj);
			System.out.print(jsonString);
		}
		catch(Exception e)
		{
			System.out.print(e);
		}
	}
}


{"field1":"Sample-1","field2":20.21,"dateField":"30-07-21"}

Summary

The ObjectMapper class of the Jackson library provides a vast number of tools to work with JSON format. In this tutorial, we learned some of the basics of this class. We learned how to serialize Java objects to JSON and how to deserialize JSON to Java objects.