Java JSON Example

Filed Under: Java

Welcome to the Java JSON Example Tutorial. JSON (JavaScript Object Notation) is text-based lightweight technology for generating human readable formatted data. JSON represent object data in the form of key-value pairs. We can have nested JSON objects too and it provides an easy way to represent arrays also.


java json, java json parser, java json example, javax.json, JsonReader, JsonWriter, JsonParser, JsonGenerator

JSON is widely used in web applications or as server response because it’s lightweight and more compact than XML. JSON objects are easy to read and write and most of the technologies provide support for JSON objects. That’s why JSON in Java web services are very popular.

JSR353 finally made into Java EE 7 and it’s the Java JSON processing API. jsonp is the reference implementation for Java JSON Processing API. We can use this in maven project by adding following dependency.


If you are using GlassFish 4.0 then you can keep the scope as provided because it’s already included in the server.

JSON API provides two ways for JSON processing:

  1. Object Model API – It’s similar to DOM Parser and good for small objects.
  2. Streaming API – It’s similar to StaX Parser and good for large objects where you don’t want to keep whole object in memory.

Some important interfaces of Java JSON API are:

  1. javax.json.JsonReader: We can use this to read JSON object or an array to JsonObject. We can get JsonReader from Json class or JsonReaderFactory.
  2. javax.json.JsonWriter: We can use this to write JSON object to output stream.
  3. This works as a pull parser and provide streaming support for reading JSON objects.
  4. We can use this to write JSON object to output source in streaming way.
  5. javax.json.Json: This is the factory class for creating JSON processing objects. This class provides the most commonly used methods for creating these objects and their corresponding factories. The factory classes provide all the various ways to create these objects.
  6. javax.json.JsonObject: JsonObject represents an immutable JSON object value.

Let’s look into the usage of Java JSON API with simple program, we have a JSON object stored in a file employee.txt as;

	"name":"Pankaj Kumar",
			"street":"El Camino Real",
			"city":"San Jose",
	"phoneNumbers":[9988664422, 1234567890],

We have java bean classes that represent above JSON format as:

package com.journaldev.model;

import java.util.Arrays;

public class Employee {

	private int id;
	private String name;
	private boolean permanent;
	private Address address;
	private long[] phoneNumbers;
	private String role;
	public int getId() {
		return id;
	public void setId(int id) { = id;
	public String getName() {
		return name;
	public void setName(String 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();

package com.journaldev.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) { = city;
	public int getZipcode() {
		return zipcode;
	public void setZipcode(int zipcode) {
		this.zipcode = zipcode;
	public String toString(){
		return getStreet() + ", "+getCity()+", "+getZipcode();

I have overridden the toString() method to return human readable String representation that we will use in our JSON implementation classes.

Java JSON Read Example

package com.journaldev.json;


import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonObject;
import javax.json.JsonReader;
import javax.json.JsonValue;

import com.journaldev.model.Address;
import com.journaldev.model.Employee;

public class EmployeeJSONReader {

	public static final String JSON_FILE="employee.txt";
	public static void main(String[] args) throws IOException {
		InputStream fis = new FileInputStream(JSON_FILE);
		//create JsonReader object
		JsonReader jsonReader = Json.createReader(fis);
		 * We can create JsonReader from Factory also
		JsonReaderFactory factory = Json.createReaderFactory(null);
		jsonReader = factory.createReader(fis);
		//get JsonObject from JsonReader
		JsonObject jsonObject = jsonReader.readObject();
		//we can close IO resource and JsonReader now
		//Retrieve data from JsonObject and create Employee bean
		Employee emp = new Employee();
		//reading arrays from json
		JsonArray jsonArray = jsonObject.getJsonArray("phoneNumbers");
		long[] numbers = new long[jsonArray.size()];
		int index = 0;
		for(JsonValue value : jsonArray){
			numbers[index++] = Long.parseLong(value.toString());
		//reading inner object from json object
		JsonObject innerJsonObject = jsonObject.getJsonObject("address");
		Address address = new Address();
		//print employee bean information


The implementation is straight forward and feels similar as getting parameters from HashMap. JsonReaderFactory implements Factory Design Pattern. Once we execute above program, we get following output.

***** Employee Details *****
Name=Pankaj Kumar
Phone Numbers=[9988664422, 1234567890]
Address=El Camino Real, San Jose, 95014

Java JSON Write Example

package com.journaldev.json;


import javax.json.Json;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import javax.json.JsonWriter;

import com.journaldev.model.Address;
import com.journaldev.model.Employee;

public class EmployeeJSONWriter {

	public static void main(String[] args) throws FileNotFoundException {

		Employee emp = createEmployee();

		JsonObjectBuilder empBuilder = Json.createObjectBuilder();
		JsonObjectBuilder addressBuilder = Json.createObjectBuilder();
		JsonArrayBuilder phoneNumBuilder = Json.createArrayBuilder();

		for (long phone : emp.getPhoneNumbers()) {
		addressBuilder.add("street", emp.getAddress().getStreet())
						.add("city", emp.getAddress().getCity())
							.add("zipcode", emp.getAddress().getZipcode());
		empBuilder.add("id", emp.getId())
					.add("name", emp.getName())
						.add("permanent", emp.isPermanent())
							.add("role", emp.getRole());
		empBuilder.add("phoneNumbers", phoneNumBuilder);
		empBuilder.add("address", addressBuilder);
		JsonObject empJsonObject =;
		System.out.println("Employee JSON String\n"+empJsonObject);
		//write to file
		OutputStream os = new FileOutputStream("emp.txt");
		JsonWriter jsonWriter = Json.createWriter(os);
		 * We can get JsonWriter from JsonWriterFactory also
		JsonWriterFactory factory = Json.createWriterFactory(null);
		jsonWriter = factory.createWriter(os);

	public static Employee createEmployee() {

		Employee emp = new Employee();
		emp.setPhoneNumbers(new long[] { 123456, 987654 });

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

		return emp;


Once we run above application, we get following response:

Employee JSON String
{"id":100,"name":"David","permanent":false,"role":"Manager","phoneNumbers":[123456,987654],"address":{"street":"BTM 1st Stage","city":"Bangalore","zipcode":560100}}

JSON object is also getting saved in emp.txt file. JsonObjectBuilder implements builder pattern that makes it very easy to use.

Java JSON Parser Example

Java JsonParser is a pull parser and we read the next element with next() method that returns an Event object. is an Enum that makes it type-safe and easy to use. We can use in switch case to set our java bean properties.

package com.journaldev.json;

import java.util.ArrayList;
import java.util.List;

import javax.json.Json;

import com.journaldev.model.Address;
import com.journaldev.model.Employee;

public class EmployeeJSONParser {

	public static final String FILE_NAME = "employee.txt";

	public static void main(String[] args) throws IOException {
		InputStream fis = new FileInputStream(FILE_NAME);

		JsonParser jsonParser = Json.createParser(fis);

		 * We can create JsonParser from JsonParserFactory also with below code
		 * JsonParserFactory factory = Json.createParserFactory(null);
		 * jsonParser = factory.createParser(fis);

		Employee emp = new Employee();
		Address address = new Address();
		String keyName = null;
		List<Long> phoneNums = new ArrayList<Long>();
		while (jsonParser.hasNext()) {
			Event event =;
			switch (event) {
			case KEY_NAME:
				keyName = jsonParser.getString();
				setStringValues(emp, address, keyName, jsonParser.getString());
				setNumberValues(emp, address, keyName, jsonParser.getLong(), phoneNums);
			case VALUE_FALSE:
				setBooleanValues(emp, address, keyName, false);
			case VALUE_TRUE:
				setBooleanValues(emp, address, keyName, true);
			case VALUE_NULL:
				// don't set anything
				// we are not looking for other events
		long[] nums = new long[phoneNums.size()];
		int index = 0;
		for(Long l :phoneNums){
			nums[index++] = l;
		//close resources

	private static void setNumberValues(Employee emp, Address address,
			String keyName, long value, List<Long> phoneNums) {
		case "zipcode":
		case "id":
			emp.setId((int) value);
		case "phoneNumbers":
			System.out.println("Unknown element with key="+keyName);	

	private static void setBooleanValues(Employee emp, Address address,
			String key, boolean value) {
			System.out.println("Unknown element with key="+key);

	private static void setStringValues(Employee emp, Address address,
			String key, String value) {
		case "name":
		case "role":
		case "city":
		case "street":
			System.out.println("Unknown Key="+key);


The major complexity comes when we need to write the logic to parse the data and sometimes it can get complex.

Since we are reading the same file as JsonReader, the output is same as EmployeeJsonReader program.

Java JsonGenerator Example

package com.journaldev.json;


import javax.json.Json;

import com.journaldev.model.Employee;

public class EmployeeJSONGenerator {

	public static void main(String[] args) throws IOException {
		OutputStream fos = new FileOutputStream("emp_stream.txt");
		JsonGenerator jsonGenerator = Json.createGenerator(fos);
		 * We can get JsonGenerator from Factory class also
		 * JsonGeneratorFactory factory = Json.createGeneratorFactory(null);
		 * jsonGenerator = factory.createGenerator(fos);
		Employee emp = EmployeeJSONWriter.createEmployee();
		jsonGenerator.writeStartObject(); // {
		jsonGenerator.write("id", emp.getId()); // "id":123
		jsonGenerator.write("name", emp.getName());
		jsonGenerator.write("role", emp.getRole());
		jsonGenerator.write("permanent", emp.isPermanent());
		jsonGenerator.writeStartObject("address") //start of address object
			.write("street", emp.getAddress().getStreet())
			.writeEnd(); //end of address object
		jsonGenerator.writeStartArray("phoneNumbers"); //start of phone num array
		for(long num : emp.getPhoneNumbers()){
		jsonGenerator.writeEnd(); // end of phone num array
		jsonGenerator.writeEnd(); // }


JsonGenerator is very easy to use and provides good performance for large data.

That’s all for Java JSON Processing API. We learned about Java JSON Parser, Read and Write examples. You can download java project from below link and play around with it.


JSONLint – Great web tool to validate JSON data
JSON Processing Reference Implementation
JSR353 JCP Page


  1. Russell says:

    Thank-you for an excellent tutorial. Your tutorials are easy enough for an old developer like me to follow to learn some new tricks before I retire!

  2. Iris says:

    Loved the article and want to suggest a great JSON tool.

  3. Ariel says:

    Nicely explained! Its very helpful. Other useful site that offers JSON Formatter online

  4. Hetarth Shah says:

    how can you set your json data dynamically? it means without set all json key in your class file.By how you can do?

  5. Rana says:

    Great !

  6. sai kiran says:

    con any tell how to convert the result set data to json

  7. Biosync says:

    Very helpful…

    keep it up….


  8. sreenivas says:

    Hi anyone can share jar files for the above examples.

    Thank You

  9. Joan says:

    Thanks for this. One of the few JSON parsing examples around that is complex enough to be really useful.

  10. Raj says:

    Hi, in servlet doPost() method I wrote the following code:

    PrintWriter out=response.getWriter();
    Object url=request.getAttribute(“authCode”);
    response.sendRedirect(“ /accessToken?grant_type=authorization_code&code=”+url+”&redirect_uri=https://localhost:8080/LinkedinMails/dem&client_id=xxxxxxxxxxxx&client_secret=xxxxxxxxxxxxxx”);

    i am getting output on browser as:

    how to retrieve value bases on access_token in servlet

  11. David Jensen says:

    Help me understand why this new JSON api is better than jaxb, ObjectMapper, or Jackson? In your example above, if I want to create a JSON string I do what you’ve shown above: jsonGenerator.write().write().write()…..etc. etc. But this is just one notch better than doing String concatenation: String foo = “{” + “name:” + “John” + “,” …… + “}”.

    This new api seems like a step backwards. Why can’t it create and parse JSON thru POJOs? What am I not seeing?

    1. Grendus says:

      The only advantage is that it’s official, which means that companies that distrust open source libraries can use it. The third party tools are much, much better.

  12. Philip Grove says:

    Fine example although it appears that it does not work with NetBeans.

    With code identical to the example and parsing a well-formed JSON file generated by NetBeans the code fails at runtime with: Unexpected char 60 at (line no=1, column no=1, offset=0).

    1. Philip Grove says:

      Don’t have a web service that used to read XML and change it to read JSON without being absolute sure that it has released the previous file.

      For some reason my Tomcat server stayed alive even though closing NetBeans should have shut it down. So the configuration pointed to one file (the correct one in JSON format) and Tomcat held another file in memory (the wrong one in XML format).

  13. swati says:

    I want to convert json object into java object .
    i am working with Spring MVC . I get Json object from Rest Controller.
    So the issue is that i want to convert json object to java object and transfer to controller.
    So all communication is happen throught RestController.

  14. Djordje Nilovic says:

    This solved my problem with converting InputStream to String because my JSON was huge and there was always OutOfMemory problem. Thank you so much!

  15. Varun says:

    Hi Pankaj,

    I have a question on JSON parsing need your help over it.

    1. Pankaj says:

      Please post the query in comments.

  16. Jayasimha says:

    i think you forgot os.close() in file writer after writing the json object. Please pardon me if i am wrong. Thank you for a wonderful explanation 馃檪

  17. Ashutosh says:

    Nicely explained.. really helpful to achieve the json response parsing.

  18. D says:

    It may not be the most convenient however it is flexible and can provides quite significant performance improvements to your particular application when necessary.

    If performance is not a factor in your application then the Google Gson api works just fine for the average android developer, Gson It is good for rapid development however also comes with a more a limited grantee and is not part of the new java 7 enterprise core.

    The stream Parser components in javax.json allow for some lightning fast parallel messaging processing capable of stripping out the components of a message you don’t need with out impacting your processing speed. you can trailer the parser to get what you need as fast as you can with out reading every thing. In systems that need to handle messages rates upwards of 10k p/s this is a must.

    I do agree the class mapping features of Gson are usefull however for strict java to java using json is not really the way to do serialization

Comments are closed.

Generic selectors
Exact matches only
Search in title
Search in content