How to create dynamic JSON by Java?


Jackson  provide Java api’s   to create JSON on runtime . These api’s can handle different type of data and objects.

Jacson API’s

Writing Root Object
JsonGenerator.writeStartObject();
JsonGenerator.writeEndObject();

Writing Sub Object
JsonGenerator.writeObjectFieldStart();
JsonGenerator.writeEndObject();

Writing Array
JsonGenerator.writeArrayFieldStart()
JsonGenerator.writeEndObject();

Writing Field Level
JsonGenerator.writeNumberField();
JsonGenerator.writeStringField();
JsonGenerator.writeBooleanField();

Pre-Requisite 

Add below jackson-databind-2.8.5.jar in your classpath or make dependency entry in pom.xml file.

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

Example

In below example by Jacson API’s generating JSON on runtime and writing on file.

package test.facingissesonit.json.jacson;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;

public class JsonStreamWriteToFile {

	public static void main(String[] args) {
		Student student = sampleStudentObject();
		try {
			JsonGenerator jsonGenerator = new JsonFactory().createGenerator(new FileOutputStream("student_data.txt"));
			// for pretty formatted printing
			jsonGenerator.setPrettyPrinter(new DefaultPrettyPrinter());
			// start root from here
			jsonGenerator.writeStartObject();

			jsonGenerator.writeNumberField("rollNumber", student.getRollNumber());
			jsonGenerator.writeStringField("firstName", student.getFirstName());
			jsonGenerator.writeStringField("lastName", student.getLastName());
			jsonGenerator.writeBooleanField("permanent", student.isPermanent());

			jsonGenerator.writeObjectFieldStart("address"); // object writing
			jsonGenerator.writeStringField("addressLine", student.getAddress().getAddressLine());
			jsonGenerator.writeStringField("city", student.getAddress().getCity());
			jsonGenerator.writeNumberField("zipCode", student.getAddress().getZipCode());
			jsonGenerator.writeEndObject(); // address object completed

			jsonGenerator.writeArrayFieldStart("phoneNumbers");
			for (long num : student.getPhoneNumbers())
				jsonGenerator.writeNumber(num);
			jsonGenerator.writeEndArray();

			 // start array writing for cities
			jsonGenerator.writeArrayFieldStart("cities");
			for (String city : student.getCities())
				jsonGenerator.writeString(city);
			// closing cities array
			jsonGenerator.writeEndArray(); 

			jsonGenerator.writeObjectFieldStart("properties");
			Set<String> keySet = student.getProperties().keySet();
			for (String key : keySet) {
				String value = student.getProperties().get(key);
				jsonGenerator.writeStringField(key, value);
			}
			// End of  properties writing
			jsonGenerator.writeEndObject();
			//End root object writing
			jsonGenerator.writeEndObject(); 

			jsonGenerator.flush();
			jsonGenerator.close();

		} catch (IOException ex) {
			ex.printStackTrace();
		}

	}

	public static Student sampleStudentObject() {

		Student student = new Student();
		student.setRollNumber(11);
		student.setFirstName("Saurabh");
		student.setLastName("Gupta");
		student.setPhoneNumbers(new long[] { 2233445566L, 3344556677L });

		Address add = new Address();
		add.setAddressLine("Lake Union Hill Way");
		add.setCity("Atlanta");
		add.setState("GA");
		add.setZipCode(50005);
		student.setAddress(add);

		List<String> cities = new ArrayList<String>();
		cities.add("Dallas");
		cities.add("San Antonio");
		cities.add("Irving");
		student.setCities(cities);

		Map<String, String> props = new HashMap<String, String>();
		props.put("age", "34 years");
		props.put("interst", "Math");
		props.put("play", "Badminton");

		student.setProperties(props);

		return student;
	}
}

Model Object

Student and Address classes are required to execute these code

package test.facingissesonit.json.jacson;

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

public class Student {
	private int rollNumber;
	private String firstName;
	private String lastName;
	private boolean permanent;
	private Address address;
	private long[] phoneNumbers;
	private List<String> cities;
	private Map<String, String> properties;
	@Override
	public String toString()
	{
		StringBuffer sb=new StringBuffer();
		sb.append("==============Student Information================\n");
		sb.append("rollNumber=").append(rollNumber).append("\n");
		sb.append("firstName=").append(firstName).append("\n");
		sb.append("lastName=").append(lastName).append("\n");
		sb.append("permanent=").append(permanent).append("\n");
		sb.append("adress=").append(address).append("\n");
		sb.append("phoneNumbers=").append(Arrays.toString(phoneNumbers)).append("\n");
		sb.append("cities=").append(Arrays.toString(cities.toArray(new String[cities.size()]))).append("\n");
		sb.append("properties=").append(properties).append("\n");
		return sb.toString();
	}
	public int getRollNumber() {
		return rollNumber;
	}
	public void setRollNumber(int rollNumber) {
		this.rollNumber = rollNumber;
	}
	public String getFirstName() {
		return firstName;
	}
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
	public String getLastName() {
		return lastName;
	}
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	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 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;
	}

}

package test.facingissesonit.json.jacson;

public class Address {
private String addressLine;
private String city;
private String state;
private int zipCode;
@Override
public String toString()
{
	StringBuffer sb=new StringBuffer();
	sb.append("AddressLine=").append(addressLine).append("\n");
	sb.append("city=").append(city).append("\n");
	sb.append("state=").append(state).append("\n");
	sb.append("zipCode=").append(zipCode).append("\n");
	return sb.toString();
}
public String getAddressLine() {
	return addressLine;
}
public void setAddressLine(String addressLine) {
	this.addressLine = addressLine;
}
public String getCity() {
	return city;
}
public void setCity(String city) {
	this.city = city;
}
public String getState() {
	return state;
}
public void setState(String state) {
	this.state = state;
}
public int getZipCode() {
	return zipCode;
}
public void setZipCode(int zipCode) {
	this.zipCode = zipCode;
}
}

Output

Generated output on Student_data.txt file

{
  "rollNumber" : 11,
  "firstName" : "Saurabh",
  "lastName" : "Gupta",
  "permanent" : false,
  "address" : {
    "addressLine" : "Lake Union Hill Way",
    "city" : "Atlanta",
    "zipCode" : 50005
  },
  "phoneNumbers" : [ 2233445566, 3344556677 ],
  "cities" : [ "Dallas", "San Antonio", "Irving" ],
  "properties" : {
    "play" : "Badminton",
    "interst" : "Math",
    "age" : "34 years"
  }
}

More Sample Code

For more java and JDBC codes follow below links

About Saurabh Gupta

My Name is Saurabh Gupta, I have approx. 10 Year of experience in Information Technology World manly in Java/J2EE. During this time I have worked with multiple organization with different client, so many technology, frameworks etc.
This entry was posted in Java, JSON and tagged , , , . Bookmark the permalink.