Read/Write JSON Using Jackson ObjectMapper, JsonParser and JsonGenerator Example

By Arvind Rai, March 01, 2015
This page will describe how to read JSON into Java object and write java object into JSON output using Jackson API. Jackson has different API like ObjectMapper, JsonParser and JsonGenerator etc. We can read JSON from different resources like String variable, file or any network. ObjectMapper is most important class which acts as codec or data binder. ObjectMapper can write java object into JSON file and read JSON file into java Object. Jackson provides faster Streaming API i.e JsonParser and JsonGenerator. JsonParser reads JSON file and JsonGenerator writes java object or map into JSON file using coded object. While creating java class to map to and from JSON we must keep a default constructor because Jackson API creates java class instance using default constructor.
Here we will cover below points.

Gradle file to Resolve Jackson JAR Dependency

Find the Gradle file to resolve Jackson JAR dependency in our project.
build.gradle
apply plugin: 'java'
apply plugin: 'eclipse'
archivesBaseName = 'Concretepage'
version = '1' 
repositories {
    mavenCentral()
}
dependencies {
   compile 'org.codehaus.jackson:jackson-mapper-asl:1.9.13'
}  

Create JSON as String by Object using ObjectMapper.writeValueAsString()

In Jackson JSON API org.codehaus.jackson.map.ObjectMapper is an important class. ObjectMapper is a codec or data binder that maps java object and JSON into each other. Here in this example we will convert java object into JSON string using writeValueAsString() method of ObjectMapper.
CreateJSONWithObjectMapper.java
package com.concretepage;
import java.io.IOException;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
public class CreateJSONWithObjectMapper {
	public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
		 ObjectMapper mapper = new ObjectMapper();
		 Address address = new Address("Dhananjaypur", "Varanasi", "UP");
		 Person person = new Person(1, "Arvind", address);
		 String json = mapper.writeValueAsString(person);
		 System.out.println(json);
	}
} 
Find the output.
{"id":1,"name":"Arvind","address":{"village":"Dhananjaypur","district":"Varanasi","state":"UP"}}
Find the class that will be used to convert into JSON and read JSON into Java object. Find the Address class.
Address.java
package com.concretepage;
public class Address {
	private String village;
	private String district;
	private String state;
	public Address(){}
	public Address(String village, String district, String state){
		this.village = village;
		this.district = district;
		this.state = state;
	}
	public String getVillage() {
		return village;
	}
	public void setVillage(String village) {
		this.village = village;
	}
	public String getDistrict() {
		return district;
	}
	public void setDistrict(String district) {
		this.district = district;
	}
	public String getState() {
		return state;
	}
	public void setState(String state) {
		this.state = state;
	}
} 
Find the person class.
Person.java
package com.concretepage;
public class Person {
	private Integer id; 
	private String name;
  	private Address address;
  	public Person(){}
  	public Person(Integer id, String name, Address address){
  		this.id = id;
  		this.name = name;
  		this.address = address;
  	}
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Address getAddress() {
		return address;
	}
	public void setAddress(Address address) {
		this.address = address;
	}
} 

Write Object into JSON file using ObjectMapper.writeValue()

In this example, we will create a java object and using ObjectMapper.writeValue() method, we will convert that java object into JSON file. writeValue() serializes java object to JSON.
WriteJSONWithObjectMapperOne.java
package com.concretepage;
import java.io.File;
import java.io.IOException;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
public class WriteJSONWithObjectMapperOne {
	public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
		 Address address = new Address("Dhananjaypur", "Varanasi", "UP");
		 Person person = new Person(1, "Arvind", address);
		 ObjectMapper mapper = new ObjectMapper();
		 mapper.writeValue(new File("D:/cp/dataOne.json"), person);
		 System.out.println("--Done--");
	}
}   
Find the output.
dataOne.json
{"id":1,"name":"Arvind","address":{"village":"Dhananjaypur","district":"Varanasi","state":"UP"}} 

Pretty Print JSON using ObjectWriter with DefaultPrettyPrinter

Jackson API can write pretty print JSON . For that we can use DefaultPrettyPrinter instance.
WriteJSONWithObjectMapperTwo.java
package com.concretepage;
import java.io.File;
import java.io.IOException;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.ObjectWriter;
import org.codehaus.jackson.util.DefaultPrettyPrinter;
public class WriteJSONWithObjectMapperTwo {
	public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
		 Address address = new Address("Dhananjaypur", "Varanasi", "UP");
		 Person person = new Person(1, "Arvind", address);
		 ObjectMapper mapper = new ObjectMapper();
		 ObjectWriter writer = mapper.writer(new DefaultPrettyPrinter());
		 writer.writeValue(new File("D:/cp/dataTwo.json"), person);
		 System.out.println("--Done--");
	}
}   
Find the output.
dataTwo.json
{
  "id" : 1,
  "name" : "Arvind",
  "address" : {
    "village" : "Dhananjaypur",
    "district" : "Varanasi",
    "state" : "UP"
  }
} 

Write java Map into JSON file using Jackson ObjectMapper

If we have data into map, that can also be converted into JSON using ObjectMapper.
WriteJSONWithObjectMapperThree.java
package com.concretepage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.ObjectWriter;
import org.codehaus.jackson.util.DefaultPrettyPrinter;
public class WriteJSONWithObjectMapperThree {
	public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
		 Map<String,Object> person = new HashMap<String,Object>();
		 Map<String,String> address = new HashMap<String,String>();
		 address.put("Vill.", "Dhananjaypur");
		 address.put("Dist.", "Varanasi");
		 address.put("State", "UP");
		 person.put("id", "1");
		 person.put("name", "Arvind");
		 person.put("address", address);
		 ObjectMapper mapper = new ObjectMapper();
		 ObjectWriter writer = mapper.writer(new DefaultPrettyPrinter());
		 writer.writeValue(new File("D:/cp/dataThree.json"), person);
		 System.out.println("--Done--");
	}
}   
Find the output.
dataThree.json
{
  "address" : {
    "Vill." : "Dhananjaypur",
    "State" : "UP",
    "Dist." : "Varanasi"
  },
  "name" : "Arvind",
  "id" : "1"
} 

Read JSON file into Object using ObjectMapper.readValue()

To read JSON file into java object, Jackson provides ObjectMapper.readValue(). Find the input JSON file.
dataOne.json
{"id":1,"name":"Arvind","address":{"village":"Dhananjaypur","district":"Varanasi","state":"UP"}} 
Now find the java class to read the JSON.
ReadJSONWithObjectMapper.java
package com.concretepage;
import java.io.FileInputStream;
import java.io.IOException;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
public class ReadJSONWithObjectMapper {
	public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
		 ObjectMapper mapper = new ObjectMapper();
		 mapper.configure(SerializationConfig.Feature.AUTO_DETECT_FIELDS, true);
		 //read from string variable
		 String json ="{\"id\":1,\"name\":\"Arvind\",\"address\":{\"village\":\"Dhananjaypur\",\"district\":\"Varanasi\",\"state\":\"UP\"}}";
		 Person person = mapper.readValue(json, Person.class);
		 System.out.println("Name:"+person.getName()+", Vill."+ person.getAddress().getVillage());
		 //Read from file
		 mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		 person = mapper.readValue(new FileInputStream("D:/cp/dataOne.json"), Person.class );
		 System.out.println("Name:"+person.getName()+", Vill."+ person.getAddress().getVillage());

	}
}
Find the output.
Name:Arvind, Vill.Dhananjaypur
Name:Arvind, Vill.Dhananjaypur


Write Object into JSON file using JsonGenerator

org.codehaus.jackson.JsonGenerator writes JSON using codec. To use JsonGenerator we can set codec as ObjectMapper() instance. In this example we will convert java object into JSON file.
WriteJSONWithJsonGeneratorOne.java
package com.concretepage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.ObjectMapper;
public class WriteJSONWithJsonGeneratorOne {
	public static void main(String[] args) throws IOException {
		JsonFactory jsonFactory = new JsonFactory(); 
		FileOutputStream file = new FileOutputStream(new File("D:/cp/infoOne.json"));
		JsonGenerator jsonGen = jsonFactory.createJsonGenerator(file, JsonEncoding.UTF8);
		Address address = new Address("Dhananjaypur", "Varanasi", "UP");
		Person person = new Person(1, "Arvind", address);
		jsonGen.setCodec(new ObjectMapper());
		jsonGen.writeObject(person);
		System.out.println("Done");
	}
} 
Find the output.
infoOne.json
{"id":1,"name":"Arvind","address":{"village":"Dhananjaypur","district":"Varanasi","state":"UP"}} 

Pretty Print using JsonGenerator

For pretty printing, Jackson provides DefaultPrettyPrinter that can be set to JsonGenerator instance.
WriteJSONWithJsonGeneratorTwo.java
package com.concretepage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.util.DefaultPrettyPrinter;
public class WriteJSONWithJsonGeneratorTwo {
	public static void main(String[] args) throws IOException {
		JsonFactory jsonFactory = new JsonFactory(); 
		FileOutputStream file = new FileOutputStream(new File("D:/cp/infoTwo.json"));
		JsonGenerator jsonGen = jsonFactory.createJsonGenerator(file, JsonEncoding.UTF8);
		Address address = new Address("Dhananjaypur", "Varanasi", "UP");
		Person person = new Person(1, "Arvind", address);
		jsonGen.setCodec(new ObjectMapper());
		jsonGen.setPrettyPrinter(new DefaultPrettyPrinter());
		jsonGen.writeObject(person);
		System.out.println("Done");
	}
} 
Find the output.
infoTwo.json
{
  "id" : 1,
  "name" : "Arvind",
  "address" : {
    "village" : "Dhananjaypur",
    "district" : "Varanasi",
    "state" : "UP"
  }
} 

Write java map into JSON file using JsonGenerator

Java map can be converted into JSON file using JsonGenerator.
WriteJSONWithJsonGeneratorThree.java
package com.concretepage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.util.DefaultPrettyPrinter;
public class WriteJSONWithJsonGeneratorThree {
	public static void main(String[] args) throws IOException {
		JsonFactory jsonFactory = new JsonFactory(); 
		FileOutputStream file = new FileOutputStream(new File("D:/cp/infoThree.json"));
		JsonGenerator jsonGen = jsonFactory.createJsonGenerator(file, JsonEncoding.UTF8);
		jsonGen.setPrettyPrinter(new DefaultPrettyPrinter());
		jsonGen.writeStartObject();
		jsonGen.writeNumberField("id", 1);
		jsonGen.writeStringField("country", "India");
		jsonGen.writeFieldName("states");
		jsonGen.writeStartArray();
		jsonGen.writeString("UP");
		jsonGen.writeString("MP");
		jsonGen.writeEndArray();
		jsonGen.writeEndObject();
		jsonGen.close();
		System.out.println("Done");
	}
} 
Find the output.
infoThree.json
{
  "id" : 1,
  "country" : "India",
  "states" : [ "UP", "MP" ]
} 

Read JSON file using JsonParser and JsonNode

org.codehaus.jackson.JsonParser reads JSON file. JsonParser can read JSON as tree returning JsonNode. Find the input JSON file.
infoTwo.json
{
  "id" : 1,
  "name" : "Arvind",
  "address" : {
    "village" : "Dhananjaypur",
    "district" : "Varanasi",
    "state" : "UP"
  }
} 
Now find the java class to read the JSON.
ReadJSONWithJsonParser.java
package com.concretepage;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.ObjectMapper;
public class ReadJSONWithJsonParser {
	public static void main(String[] args) throws JsonParseException, IOException {
		JsonFactory jsonFactory = new JsonFactory();
		JsonParser jp = jsonFactory.createJsonParser(new File("D:/cp/infoTwo.json"));
		jp.setCodec(new ObjectMapper());
		JsonNode jsonNode = jp.readValueAsTree();
		readJsonData(jsonNode);
	}
	static void readJsonData(JsonNode jsonNode) {
		Iterator<Map.Entry<String, JsonNode>> ite = jsonNode.getFields();
		while(ite.hasNext()){
			Map.Entry<String, JsonNode> entry = ite.next();
			if(entry.getValue().isObject()) {
				readJsonData(entry.getValue());
			} else {
			    System.out.println("key:"+entry.getKey()+", value:"+entry.getValue());
			}
		}
	}
} 
Find the output.
key:id, value:1
key:name, value:"Arvind"
key:village, value:"Dhananjaypur"
key:district, value:"Varanasi"
key:state, value:"UP" 

Download Complete Source Code

POSTED BY
ARVIND RAI
ARVIND RAI







©2024 concretepage.com | Privacy Policy | Contact Us