Jackson JSON Java Parser API Example Tutorial

Filed Under: Java

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.


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": [
  "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;
	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;
	public String toString(){
		StringBuilder sb = new StringBuilder();
		sb.append("***** Employee Details *****\n");
		sb.append("Phone Numbers="+Arrays.toString(getPhoneNumbers())+"\n");
		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.setPhoneNumbers(new long[] { 123456, 987654 });

		Address add = new Address();
		add.setStreet("BTM 1st Stage");

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

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

		return emp;


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

Employee Object
***** Employee Details *****
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();
	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.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;
		//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();
			}else if("name".equals(name)){
			}else if("permanent".equals(name)){
			}else if("address".equals(name)){
				//nested object, recursive call
				parseJSON(jsonParser, emp, phoneNums, insidePropertiesObj);
			}else if("street".equals(name)){
			}else if("city".equals(name)){
			}else if("zipcode".equals(name)){
			}else if("phoneNumbers".equals(name)){
				while (jsonParser.nextToken() != JsonToken.END_ARRAY) {
			}else if("role".equals(name)){
			}else if("cities".equals(name)){
				while (jsonParser.nextToken() != JsonToken.END_ARRAY) {
			}else if("properties".equals(name)){
				while(jsonParser.nextToken() != JsonToken.END_OBJECT){
					String key = jsonParser.getCurrentName();
					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
			for(long num : emp.getPhoneNumbers())
		jsonGenerator.writeStringField("role", emp.getRole());
		jsonGenerator.writeArrayFieldStart("cities"); //start cities array
		for(String city : emp.getCities())
		jsonGenerator.writeEndArray(); //closing cities array
			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 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.

Reference: Jackson GitHub Page


  1. aysenur says:

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

  2. Sheri says:

    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.

  3. Ardalan says:

    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?


  4. renu says:


    I have a json like this from rest API.please help me to convert this to java object

  5. sankar says:

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

  6. sai says:

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

  7. @Di says:

    can we use jackson to pass excel file as input and produce json file as output. (don’t want to read pojo manually).
    how i can do it. do you have example

  8. veena rao says:

    my json string s like
    { “car”=”Alto”, “”type”=”petrol”,”year”=”2001″}
    { “car”=”benz”, “”type”=”diesel”,”year”=”2011″}
    { “car”=”i20”, “”type”=”diesel”,”year”=”2006″}

    i want to add all these values as MAP.
    for (String object:object1 ) {
    Map map = new HashMap();
    ObjectMapper mapper = new ObjectMapper();
    map = mapper.readValue(object, new TypeReference<Map>(){});

    But this this taking the latest value,
    how can i make sure it reads all values in the map.

    1. sankar says:


      I have same json file format data, how did u do that? I have million records in json file I need to read.

      how to do with object mapper?

  9. San says:

    {“Recipients”: [{
    “Addresses”: [
    “Add1″:”123 st”,
    {“AddressId”:22,”Add1″:”123 st”,”Add2″:”50″,”Add3″:””,
    “MastDet”: [{“Mast_Id”: 1111,”Mast_Type”: “State”,},
    {“Mast_Id”: 222,”Mast_Type”: “Country”,”Mast_Value”: “AAA123”,}],
    “Value”: [{“Value”: “Given”,”Country”: “United States of America”,
    “StartDate”: null,}]}]}

    how to read this one the example please can someone help me

  10. Rakesh says:

    Hi Pankaj,
    Nice Article.
    I have one scenario where I am not aware the Structure/Layout of the JSON file. I have to read the file and mask few fields and then again write the data into new JSON file.
    can you Please give one example of it

  11. dorai says:

    how do we convert json to yaml format…

    1. shivani verma says:

      hey i got an issue … i am getting an array of songs list in my json response now i want to categories them according to genre and pass the data accordingly in different fragments but i dont know how to do that can anyone help me ??

  12. rajat says:

    Thank You for sharing wonderful knowledge, I have I doubt according to auto creation of variable for setter and getter, But what if someone insert one more field in JSON array and we don’t know what it will be It might be anything,How we can get that variable value automatically from the POJO of that JSON variable, In your Address POJO you declare toString method which is custom method(what I understand), How I can automatically return that variable using its getter method in toString method.
    I wish I explain my doubt clearly.

    1. rajat says:

      Sorry for English, I missed “I have 1 doubt”

    2. Pankaj says:

      If you will add a new field to JSON, then you will have to make corresponding changes to POJO class too. And if required, then in the toString method too. The JSON and Java Object should match with each other to work.

  13. TahorSuiJuris says:


  14. Rohit Singh says:

    Nicely explained the Jackson JSON parser, thank you pankaj for this wonderful blog.

  15. Vincent says:

    very good

  16. Troy Torgerson says:

    I have been looking for exactly this example for a long time now. I have some complex JSON coming in from a web service and have been unable to find a single example of how to map out the complex JSON into JAVA objects.

    This couldn’t be any better. and very concise as well.

  17. Cowtowncoder says:

    I would strongly recommend using Maven coordinates for more up to date version: latest release is 2.7.4, and most frameworks use at least 2.5.

  18. Mahdi Mohammadnezhad says:


    i need to make a JSON streaming api with java. i mean i need to generate JSON for every 3 second to do some test on client.

    can you please help me t do that with java language. i searched alot but coudln’t find any solution

  19. Vishnu says:

    I am trying to send the objectmapper data through HttpPost like,

    httpPost.setEntity(new StringEntity(objectMapper.toString()));
    HttpResponse response = httpClient.execute(httpPost);

    I am getting “code”: 400, “message”: “Bad Request: Error parsing JSON, malformed JSON”
    However using json.jar the same JSON input is working. Any pointers..?

  20. mohan says:

    such a very nice post on jackson, well explained Pankaj..

  21. Samsudeen says:

    Perfect example it really solved a problem i have been facing for over a week.

  22. Senthil says:

    This blog was very helpful in understanding the described capability. Does Jackson library have a feature which i can use to sanitize the JSON content for any malicious javascript content ?

    This library from OWASP is said to do it but, when it contains a javascript or invalid formed JSON, it formats the input to a proper JSON string, rather than raising any violation exception. https://www.owasp.org/index.php/OWASP_JSON_Sanitizer#tab=Output

    Could you help me know if Jackson has any such capability ?

  23. Russell Bateman says:

    Impressively accurate tutorial, Pankaj. I like it when I don’t have to fix stuff to get something to work.

    Thank you very much!

  24. Rouche says:

    Ok nevermind my old comment.

    This is weird i was unable to get the tutorial there opening.
    Everything is there.


  25. Rouche says:


    This should be included in their wiki!

    It would be cool to have a Base64 example 🙂

  26. Shajee says:

    Very useful article. Jackson API in itself is very beneficial and the process of using JsonGenerator has made it even more simple. I had been stuck with json auto-formatting and Jackson has been a wonderful support and your samples helped a lot.

    Cheers !!

  27. Fernando Simoes says:

    Pankaj, I’m just taking some time to express my gratitude for you do share so many well-written articles, specially this one. I’ve been googling back to this specific article for so many times I’ve already bookmarked it. Thanks a lot, I really appreciate it.

  28. CoryD says:

    I would just like to add I had to use the @JsonProperty & @JsonCreator annotations to read the json back into my model using the ObjectMapper. Otherwise I would get instantiation errors.
    -Also I am using the “com.fasterxml.jackson” libraries.

    1. Pankaj says:

      Can you provide the dependecy details you are using, also the version. The program works fine for latest version, I am not sure if older version has any dependencies regarding these annotations.

  29. Abhishek says:

    It is very helpful post.

  30. bobanahalf says:

    Nice post. Very helpful examples.

  31. Rene Cejas Bolecek says:

    Excellent post on Jackson libs! Thks a lot very useful.

  32. subbareddy says:

    nice post on json…………

  33. Devesh Anand says:

    If u here to help ue thn plz help me to develop application in spring in which it ask for select file from hard drive, and dislay the content of file onto the browser, and at the same time one save buttom will there in which it will ask for saving the file into one location in the hard drive.

Leave a Reply

Your email address will not be published. Required fields are marked *

Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages