Tutorial

Jackson JSON Java Parser API Example Tutorial

Published on August 3, 2022
author

Pankaj

Jackson JSON Java Parser API Example Tutorial

Jackson JSON Java Parser is very popular and used in Spring framework too. Java JSON Processing API is not very user friendly and doesn’t provide features for automatic transformation from Json to Java object and vice versa. Luckily we have some alternative APIs that we can use for JSON processing. In last article we learned about Google Gson API and saw how easy to use it.

Jackson JSON Java Parser

Jackson JSON Parser Java API Example Tutorial, ObjectMapper, JSON to Java Object, Java Object to JSON To use Jackson JSON Java API in our project, we can add it to the project build path or if you are using maven, we can add below dependency.

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

jackson-databind jar depends on jackson-core and jackson-annotations libraries, so if you are adding them directly to build path, make sure you add all three otherwise you will get runtime error. Jackson JSON Parser API provides easy way to convert JSON to POJO Object and supports easy conversion to Map from JSON data. Jackson supports generics too and directly converts them from JSON to object.

Jackson JSON Example

For our example for JSON to POJO/Java object conversion, we will take a complex example with nested object and arrays. We will use arrays, list and Map in java objects for conversion. Our complex json is stored in a file employee.txt with below structure:

{
  "id": 123,
  "name": "Pankaj",
  "permanent": true,
  "address": {
    "street": "Albany Dr",
    "city": "San Jose",
    "zipcode": 95129
  },
  "phoneNumbers": [
    123456,
    987654
  ],
  "role": "Manager",
  "cities": [
    "Los Angeles",
    "New York"
  ],
  "properties": {
    "age": "29 years",
    "salary": "1000 USD"
  }
}

We have following java classes corresponding to the json data.

package com.journaldev.jackson.model;

public class Address {
	
	private String street;
	private String city;
	private int zipcode;
	
	public String getStreet() {
		return street;
	}
	public void setStreet(String street) {
		this.street = street;
	}
	public String getCity() {
		return city;
	}
	public void setCity(String city) {
		this.city = city;
	}
	public int getZipcode() {
		return zipcode;
	}
	public void setZipcode(int zipcode) {
		this.zipcode = zipcode;
	}
	
	@Override
	public String toString(){
		return getStreet() + ", "+getCity()+", "+getZipcode();
	}
}

Address class corresponds to the inner object in the root json data.

package com.journaldev.jackson.model;

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

public class Employee {

	private int id;
	private String name;
	private boolean permanent;
	private Address address;
	private long[] phoneNumbers;
	private String role;
	private List<String> cities;
	private Map<String, String> properties;
	
	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 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 String getRole() {
		return role;
	}
	public void setRole(String role) {
		this.role = role;
	}
	
	@Override
	public String toString(){
		StringBuilder sb = new StringBuilder();
		sb.append("***** Employee Details *****\n");
		sb.append("ID="+getId()+"\n");
		sb.append("Name="+getName()+"\n");
		sb.append("Permanent="+isPermanent()+"\n");
		sb.append("Role="+getRole()+"\n");
		sb.append("Phone Numbers="+Arrays.toString(getPhoneNumbers())+"\n");
		sb.append("Address="+getAddress()+"\n");
		sb.append("Cities="+Arrays.toString(getCities().toArray())+"\n");
		sb.append("Properties="+getProperties()+"\n");
		sb.append("*****************************");
		
		return sb.toString();
	}
	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;
	}
}

Employee is the java bean representing the root json object. Now let’s see how can we transform JSON to java object using Jackson JSON parser API.

package com.journaldev.jackson.json;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.journaldev.jackson.model.Address;
import com.journaldev.jackson.model.Employee;


public class JacksonObjectMapperExample {

	public static void main(String[] args) throws IOException {
		
		//read json file data to String
		byte[] jsonData = Files.readAllBytes(Paths.get("employee.txt"));
		
		//create ObjectMapper instance
		ObjectMapper objectMapper = new ObjectMapper();
		
		//convert json string to object
		Employee emp = objectMapper.readValue(jsonData, Employee.class);
		
		System.out.println("Employee Object\n"+emp);
		
		//convert Object to json string
		Employee emp1 = createEmployee();
		//configure Object mapper for pretty print
		objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
		
		//writing to console, can write to any output stream such as file
		StringWriter stringEmp = new StringWriter();
		objectMapper.writeValue(stringEmp, emp1);
		System.out.println("Employee JSON is\n"+stringEmp);
	}
	
	public static Employee createEmployee() {

		Employee emp = new Employee();
		emp.setId(100);
		emp.setName("David");
		emp.setPermanent(false);
		emp.setPhoneNumbers(new long[] { 123456, 987654 });
		emp.setRole("Manager");

		Address add = new Address();
		add.setCity("Bangalore");
		add.setStreet("BTM 1st Stage");
		add.setZipcode(560100);
		emp.setAddress(add);

		List<String> cities = new ArrayList<String>();
		cities.add("Los Angeles");
		cities.add("New York");
		emp.setCities(cities);

		Map<String, String> props = new HashMap<String, String>();
		props.put("salary", "1000 Rs");
		props.put("age", "28 years");
		emp.setProperties(props);

		return emp;
	}

}

When we run above program, you will get following output.

Employee Object
***** Employee Details *****
ID=123
Name=Pankaj
Permanent=true
Role=Manager
Phone Numbers=[123456, 987654]
Address=Albany Dr, San Jose, 95129
Cities=[Los Angeles, New York]
Properties={age=29 years, salary=1000 USD}
*****************************
Employee JSON is
//printing same as above json file data

com.fasterxml.jackson.databind.ObjectMapper is the most important class in Jackson API that provides readValue() and writeValue() methods to transform JSON to Java Object and Java Object to JSON. ObjectMapper class can be reused and we can initialize it once as Singleton object. There are so many overloaded versions of readValue() and writeValue() methods to work with byte array, File, input/output stream and Reader/Writer objects.

Jackson JSON - Converting JSON to Map

Sometimes we have a JSON object like below, in data.txt file:

{
  "name": "David",
  "role": "Manager",
  "city": "Los Angeles"
}

and we want to convert it to a Map and not to java object with same properties and keys. We can do it very easily in Jackson JSON API with two methods with below code:

//converting json to Map
byte[] mapData = Files.readAllBytes(Paths.get("data.txt"));
Map<String,String> myMap = new HashMap<String, String>();

ObjectMapper objectMapper = new ObjectMapper();
myMap = objectMapper.readValue(mapData, HashMap.class);
System.out.println("Map is: "+myMap);

//another way
myMap = objectMapper.readValue(mapData, new TypeReference<HashMap<String,String>>() {});
System.out.println("Map using TypeReference: "+myMap);

Once we execute above snippet, we get following output:

Map is: {name=David, role=Manager, city=Los Angeles}
Map using TypeReference: {name=David, role=Manager, city=Los Angeles}

Jackson JSON - Read Specific JSON Key

Sometimes we have json data and we are interested in only few of the keys values, so in that case converting whole JSON to object is not a good idea. Jackson JSON API provides option to read json data as tree like DOM Parser and we can read specific elements of JSON object through this. Below code provides snippet to read specific entries from json file.

//read json file data to String
byte[] jsonData = Files.readAllBytes(Paths.get("employee.txt"));

//create ObjectMapper instance
ObjectMapper objectMapper = new ObjectMapper();

//read JSON like DOM Parser
JsonNode rootNode = objectMapper.readTree(jsonData);
JsonNode idNode = rootNode.path("id");
System.out.println("id = "+idNode.asInt());

JsonNode phoneNosNode = rootNode.path("phoneNumbers");
Iterator<JsonNode> elements = phoneNosNode.elements();
while(elements.hasNext()){
	JsonNode phone = elements.next();
	System.out.println("Phone No = "+phone.asLong());
}

We get following output when we execute above code snippet.

id = 123
Phone No = 123456
Phone No = 987654

Jackson JSON - Edit JSON Document

Jackson JSON Java API provide useful methods to add, edit and remove keys from JSON data and then we can save it as new json file or write it to any stream. Below code shows us how to do this easily.

byte[] jsonData = Files.readAllBytes(Paths.get("employee.txt"));

ObjectMapper objectMapper = new ObjectMapper();

//create JsonNode
JsonNode rootNode = objectMapper.readTree(jsonData);

//update JSON data
((ObjectNode) rootNode).put("id", 500);
//add new key value
((ObjectNode) rootNode).put("test", "test value");
//remove existing key
((ObjectNode) rootNode).remove("role");
((ObjectNode) rootNode).remove("properties");
objectMapper.writeValue(new File("updated_emp.txt"), rootNode);

If you will execute above code and look for the new file, you will notice that it doesn’t have “role” and “properties” key. You will also notice that “id” value is updated to 500 and a new key “test” is added to updated_emp.txt file.

Jackson JSON Streaming API Example

Jackson JSON Java API also provide streaming support that is helpful in working with large json data because it reads the whole file as tokens and uses less memory. The only problem with streaming API is that we need to take care of all the tokens while parsing the JSON data. If we have json data as {“role”:“Manager”} then we will get following tokens in order - { (start object), “role” (key name), “Manager” (key value) and } (end object). Colon (:) is the delimiter in JSON and hence not considered as a token.

package com.journaldev.jackson.json;

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

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.journaldev.jackson.model.Address;
import com.journaldev.jackson.model.Employee;

public class JacksonStreamingReadExample {

	public static void main(String[] args) throws JsonParseException, IOException {
		
		//create JsonParser object
		JsonParser jsonParser = new JsonFactory().createParser(new File("employee.txt"));
		
		//loop through the tokens
		Employee emp = new Employee();
		Address address = new Address();
		emp.setAddress(address);
		emp.setCities(new ArrayList<String>());
		emp.setProperties(new HashMap<String, String>());
		List<Long> phoneNums = new ArrayList<Long>();
		boolean insidePropertiesObj=false;
		
		parseJSON(jsonParser, emp, phoneNums, insidePropertiesObj);
		
		long[] nums = new long[phoneNums.size()];
		int index = 0;
		for(Long l :phoneNums){
			nums[index++] = l;
		}
		emp.setPhoneNumbers(nums);
		
		jsonParser.close();
		//print employee object
		System.out.println("Employee Object\n\n"+emp);
	}

	private static void parseJSON(JsonParser jsonParser, Employee emp,
			List<Long> phoneNums, boolean insidePropertiesObj) throws JsonParseException, IOException {
		
		//loop through the JsonTokens
		while(jsonParser.nextToken() != JsonToken.END_OBJECT){
			String name = jsonParser.getCurrentName();
			if("id".equals(name)){
				jsonParser.nextToken();
				emp.setId(jsonParser.getIntValue());
			}else if("name".equals(name)){
				jsonParser.nextToken();
				emp.setName(jsonParser.getText());
			}else if("permanent".equals(name)){
				jsonParser.nextToken();
				emp.setPermanent(jsonParser.getBooleanValue());
			}else if("address".equals(name)){
				jsonParser.nextToken();
				//nested object, recursive call
				parseJSON(jsonParser, emp, phoneNums, insidePropertiesObj);
			}else if("street".equals(name)){
				jsonParser.nextToken();
				emp.getAddress().setStreet(jsonParser.getText());
			}else if("city".equals(name)){
				jsonParser.nextToken();
				emp.getAddress().setCity(jsonParser.getText());
			}else if("zipcode".equals(name)){
				jsonParser.nextToken();
				emp.getAddress().setZipcode(jsonParser.getIntValue());
			}else if("phoneNumbers".equals(name)){
				jsonParser.nextToken();
				while (jsonParser.nextToken() != JsonToken.END_ARRAY) {
					phoneNums.add(jsonParser.getLongValue());
				}
			}else if("role".equals(name)){
				jsonParser.nextToken();
				emp.setRole(jsonParser.getText());
			}else if("cities".equals(name)){
				jsonParser.nextToken();
				while (jsonParser.nextToken() != JsonToken.END_ARRAY) {
					emp.getCities().add(jsonParser.getText());
				}
			}else if("properties".equals(name)){
				jsonParser.nextToken();
				while(jsonParser.nextToken() != JsonToken.END_OBJECT){
					String key = jsonParser.getCurrentName();
					jsonParser.nextToken();
					String value = jsonParser.getText();
					emp.getProperties().put(key, value);
				}
			}
		}
	}

}

JsonParser is the jackson json streaming API to read json data, we are using it to read data from the file and then parseJSON() method is used to loop through the tokens and process them to create our java object. Notice that parseJSON() method is called recursively for “address” because it’s a nested object in the json data. For parsing arrays, we are looping through the json document. We can use JsonGenerator class to generate json data with streaming API.

package com.journaldev.jackson.json;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Set;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
import com.journaldev.jackson.model.Employee;

public class JacksonStreamingWriteExample {

	public static void main(String[] args) throws IOException {
		Employee emp = JacksonObjectMapperExample.createEmployee();

		JsonGenerator jsonGenerator = new JsonFactory()
				.createGenerator(new FileOutputStream("stream_emp.txt"));
		//for pretty printing
		jsonGenerator.setPrettyPrinter(new DefaultPrettyPrinter());
		
		jsonGenerator.writeStartObject(); // start root object
		jsonGenerator.writeNumberField("id", emp.getId());
		jsonGenerator.writeStringField("name", emp.getName());
		jsonGenerator.writeBooleanField("permanent", emp.isPermanent());
		
		jsonGenerator.writeObjectFieldStart("address"); //start address object
			jsonGenerator.writeStringField("street", emp.getAddress().getStreet());
			jsonGenerator.writeStringField("city", emp.getAddress().getCity());
			jsonGenerator.writeNumberField("zipcode", emp.getAddress().getZipcode());
		jsonGenerator.writeEndObject(); //end address object
		
		jsonGenerator.writeArrayFieldStart("phoneNumbers");
			for(long num : emp.getPhoneNumbers())
				jsonGenerator.writeNumber(num);
		jsonGenerator.writeEndArray();
		
		jsonGenerator.writeStringField("role", emp.getRole());
		
		jsonGenerator.writeArrayFieldStart("cities"); //start cities array
		for(String city : emp.getCities())
			jsonGenerator.writeString(city);
		jsonGenerator.writeEndArray(); //closing cities array
		
		jsonGenerator.writeObjectFieldStart("properties");
			Set<String> keySet = emp.getProperties().keySet();
			for(String key : keySet){
				String value = emp.getProperties().get(key);
				jsonGenerator.writeStringField(key, value);
			}
		jsonGenerator.writeEndObject(); //closing properties
		jsonGenerator.writeEndObject(); //closing root object
		
		jsonGenerator.flush();
		jsonGenerator.close();
	}

}

JsonGenerator is easy to use in comparison to JsonParser. That’s all for quick reference tutorial to Jackson JSON Parser Java API. Jackson JSON Java API is easy to use and provide a lot of options for the ease of developers working with JSON data. Download project from below link and play around with it to explore more options about Jackson Json API.

Download Jackson JSON Project

Reference: Jackson GitHub Page

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Pankaj

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
July 24, 2020

Thanks for this wonderful article. I am using your example for reading data from file and updating it however i want to write to data into the same file . what api should i use. I am giving same file location for updating the value but its not getting written into the same file .please guide.

- Neha

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    June 26, 2020

    { “0003007028”: { “offers”: { “16132249”: { “offerId”: “16132249”, “deleted”: false }, “136850888”: { “offerId”: “136850888”, “deleted”: false } } }, “0002113896”: { “offers”: { “707341053”: { “offerId”: “707341053”, “deleted”: false } } }, “000007o002”: { “offers”: { “16132249”: { “offerId”: “16132249”, “deleted”: false }, “136850888”: { “offerId”: “136850888”, “deleted”: false } } } } Can someone help how to map this complex json to pojo. I appreciate your time to help this. Thanks - Akash

    - Akash Shindhe

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      June 2, 2020

      Hello, this is a very excellent article. very well written and read. thank you for being thorough. I’m really strugging with deserializing a JSON data due to nulls. I’m lost and confused :). trying to unmarshal a JSON in to JAVA POJO. but, I can’t seem to resolve this error. would anyone be able to assist ? greatly appreciated. Caused by: java.lang.IllegalArgumentException: Unrecognized Type: [null] at com.fasterxml.jackson.databind.type.TypeFactory._constructType(TypeFactory.java:517)[123:com.fasterxml.jackson.core.jackson-databind:2.6.3] at com.fasterxml.jackson.databind.type.TypeFactory.constructType(TypeFactory.java:470)[123:com.fasterxml.jackson.core.jackson-databind:2.6.3] at com.fasterxml.jackson.databind.deser.BasicDeserializerFactory.constructCreatorProperty(BasicDeserializerFactory.java:842)[123:com.fasterxml.jackson.core.jackson-databind:2.6.3] at com.fasterxml.jackson.databind.deser.BasicDeserializerFactory._addDeserializerConstructors(BasicDeserializerFactory.java:463)[123:com.fasterxml.jackson.core.jackson-databind:2.6.3] at com.fasterxml.jackson.databind.deser.BasicDeserializerFactory._constructDefaultValueInstantiator(BasicDeserializerFactory.java:324)[123:com.fasterxml.jackson.core.jackson-databind:2.6.3] at com.fasterxml.jackson.databind.deser.BasicDeserializerFactory.findValueInstantiator(BasicDeserializerFactory.java:254)[123:com.fasterxml.jackson.core.jackson-databind:2.6.3] at com.fasterxml.jackson.databind.deser.BeanDeserializerFactory.buildBeanDeserializer(BeanDeserializerFactory.java:222)[123:com.fasterxml.jackson.core.jackson-databind:2.6.3] at com.fasterxml.jackson.databind.deser.BeanDeserializerFactory.createBeanDeserializer(BeanDeserializerFactory.java:142)[123:com.fasterxml.jackson.core.jackson-databind:2.6.3] at com.fasterxml.jackson.databind.deser.DeserializerCache._createDeserializer2(DeserializerCache.java:403)[123:com.fasterxml.jackson.core.jackson-databind:2.6.3] at com.fasterxml.jackson.databind.deser.DeserializerCache._createDeserializer(DeserializerCache.java:352)[123:com.fasterxml.jackson.core.jackson-databind:2.6.3] at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCache2(DeserializerCache.java:264)[123:com.fasterxml.jackson.core.jackson-databind:2.6.3] {“name”:“DEGT”,“data”:[null,“64.5471”,null,“57.5209”,null,“57.9785”,null,“60.53”],“arraySizes”:[8]},{…

      - Gary Mills

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        April 1, 2020

        I am getting this error with those files, I have added all three jars to the pom.xml, I cant quite figure out why I am getting this error (First part of the code) Exception in thread “main” java.lang.NoClassDefFoundError: com/fasterxml/jackson/databind/ObjectMapper

        - John

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          January 30, 2019

          I wanted to learn for a long time. Thank you very much ! :)

          - aysenur

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            January 7, 2019

            Thank you very much for the detailed post on this. I have been struggling to find what was wrong with my jackson json API which I wanted to build in a Java 6 environment. This helped a lot. My build got failed since I have used the latest version (com.fasterxml.jackson.core 2.9.6) saying com.fasterxml.jackson.databind.JsonNode cannot be resolved. Then I downgraded the version to com.fasterxml.jackson.core 2.2.3 and used the objectMapper.readValue() and it worked for java 6 as well without any issue.

            - Sheri

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              December 4, 2018

              Hi, I have an interesting JSON String and I could not parse it because looks different. I just need to take a Status and message can somebody help me? {“certInfo”:{“data”:null,”responseStatus”:{“status”:”ERROR”,”messages”:[“error.socket_timeout”],”redirectUrl”:””}},”vulnerabilities”:{“data”:null,”responseStatus”:{“status”:”ERROR”,”messages”:[“error.socket_timeout”],”redirectUrl”:””}},”serverConfig”:{“data”:null,”responseStatus”:{“status”:”ERROR”,”messages”:[“error.socket_timeout”],”redirectUrl”:””}}}

              - Ardalan

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                November 29, 2018

                [{ “Key”:“10” “Record”: { “customeraccountno”:“SCBL234A10” “customerfirstname”:“kishore” “customerlastname”:“kasukarthi” “landlineno”:“11223344” } }] I have a json like this from rest API.please help me to convert this to java object

                - renu

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  November 7, 2018

                  Really nice post, I have json data in file {“id”=“123”, “ip”=“10.1.2.3”}{id"=“123”, “ip”=“10.1.2.4”}…{} I need to read all json line by line. pls suggest.

                  - sankar

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    July 11, 2018

                    while reading JSON through streaming api , if any of the json element is not present while parsing then how to handle that exception ?

                    - sai

                      Try DigitalOcean for free

                      Click below to sign up and get $200 of credit to try our products over 60 days!

                      Sign up

                      Join the Tech Talk
                      Success! Thank you! Please check your email for further details.

                      Please complete your information!

                      Featured on Community

                      Get our biweekly newsletter

                      Sign up for Infrastructure as a Newsletter.

                      Hollie's Hub for Good

                      Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

                      Become a contributor

                      Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                      Welcome to the developer cloud

                      DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

                      Learn more