Tutorial

Java JSON Example

Published on August 4, 2022
author

Pankaj

Java JSON Example

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, 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.

<dependency>
	<groupId>org.glassfish</groupId>
  	<artifactId>javax.json</artifactId>
  	<version>1.0.2</version>
</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. javax.json.stream.JsonParser: This works as a pull parser and provide streaming support for reading JSON objects.
  4. javax.json.stream.JsonGenerator: 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;

{
	"id":123,
	"name":"Pankaj Kumar",
	"permanent":true,
	"address":{
			"street":"El Camino Real",
			"city":"San Jose",
			"zipcode":95014
		},
	"phoneNumbers":[9988664422, 1234567890],
	"role":"Developer"
}

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) {
		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());
		sb.append("\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) {
		this.city = city;
	}
	public int getZipcode() {
		return zipcode;
	}
	public void setZipcode(int zipcode) {
		this.zipcode = zipcode;
	}
	
	@Override
	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 java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

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
		jsonReader.close();
		fis.close();
		
		//Retrieve data from JsonObject and create Employee bean
		Employee emp = new Employee();
		
		emp.setId(jsonObject.getInt("id"));
		emp.setName(jsonObject.getString("name"));
		emp.setPermanent(jsonObject.getBoolean("permanent"));
		emp.setRole(jsonObject.getString("role"));
		
		//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());
		}
		emp.setPhoneNumbers(numbers);
		
		//reading inner object from json object
		JsonObject innerJsonObject = jsonObject.getJsonObject("address");
		Address address = new Address();
		address.setStreet(innerJsonObject.getString("street"));
		address.setCity(innerJsonObject.getString("city"));
		address.setZipcode(innerJsonObject.getInt("zipcode"));
		emp.setAddress(address);
		
		//print employee bean information
		System.out.println(emp);
		
	}

}

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 *****
ID=123
Name=Pankaj Kumar
Permanent=true
Role=Developer
Phone Numbers=[9988664422, 1234567890]
Address=El Camino Real, San Jose, 95014
*****************************

Java JSON Write Example

package com.journaldev.json;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;

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()) {
			phoneNumBuilder.add(phone);
		}
		
		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 = empBuilder.build();
		
		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);
		*/
		jsonWriter.writeObject(empJsonObject);
		jsonWriter.close();
	}
	

	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);

		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. javax.json.stream.JsonParser.Event 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.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.json.Json;
import javax.json.stream.JsonParser;
import javax.json.stream.JsonParser.Event;

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 = jsonParser.next();
			switch (event) {
			case KEY_NAME:
				keyName = jsonParser.getString();
				break;
			case VALUE_STRING:
				setStringValues(emp, address, keyName, jsonParser.getString());
				break;
			case VALUE_NUMBER:
				setNumberValues(emp, address, keyName, jsonParser.getLong(), phoneNums);
				break;
			case VALUE_FALSE:
				setBooleanValues(emp, address, keyName, false);
				break;
			case VALUE_TRUE:
				setBooleanValues(emp, address, keyName, true);
				break;
			case VALUE_NULL:
				// don't set anything
				break;
			default:
				// we are not looking for other events
			}
		}
		emp.setAddress(address);
		long[] nums = new long[phoneNums.size()];
		int index = 0;
		for(Long l :phoneNums){
			nums[index++] = l;
		}
		emp.setPhoneNumbers(nums);
		
		System.out.println(emp);
		
		//close resources
		fis.close();
		jsonParser.close();
	}

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

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

	private static void setStringValues(Employee emp, Address address,
			String key, String value) {
		switch(key){
		case "name":
			emp.setName(value);
			break;
		case "role":
			emp.setRole(value);
			break;
		case "city":
			address.setCity(value);
			break;
		case "street":
			address.setStreet(value);
			break;
		default:
			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 java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.json.Json;
import javax.json.stream.JsonGenerator;

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())
			.write("city",emp.getAddress().getCity())
			.write("zipcode",emp.getAddress().getZipcode())
			.writeEnd(); //end of address object
		
		jsonGenerator.writeStartArray("phoneNumbers"); //start of phone num array
		for(long num : emp.getPhoneNumbers()){
			jsonGenerator.write(num);
		}
		jsonGenerator.writeEnd(); // end of phone num array
		jsonGenerator.writeEnd(); // }
		
		jsonGenerator.close();
		
	}

}

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.

Download Java JSON Project

References: JSONLint - Great web tool to validate JSON data JSON Processing Reference Implementation JSR353 JCP 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
February 8, 2020

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!

- Russell

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    June 25, 2018

    Loved the article and want to suggest a great JSON tool. https://jsonformatter.org

    - Iris

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      August 24, 2017

      Nicely explained! Its very helpful. Other useful site that offers JSON Formatter online https://jsonformatter-online.com

      - Ariel

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        June 8, 2017

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

        - Hetarth Shah

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          May 10, 2017

          Great !

          - Rana

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            March 27, 2017

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

            - sai kiran

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              July 29, 2016

              Very helpful… keep it up… Thanks.

              - Biosync

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                July 20, 2015

                Hi anyone can share jar files for the above examples. Thank You

                - sreenivas

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  June 28, 2015

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

                  - Joan

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    November 26, 2014

                    Hi, in servlet doPost() method I wrote the following code: PrintWriter out=response.getWriter(); Object url=request.getAttribute(“authCode”); response.sendRedirect(“https://www.linkedin.com/uas/oauth2 /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: {“access_token”:“AQVZ3XLxAkNZ7LowhdRP5TNoIx5svkCNmn10XQgwZb3I8tAC_JUTL44u43jJehYXtRmr2RwG9nNThkMrCVnbhqaZpJftdmK3MI1joYcHMQDozYfsWLy5FDs7POyNqK2WUuPNpJHUzHJflkPbQMMkpWAvNTeuza6PoDcb5otRN8jWqqxVE”,“expires_in”:5183999} how to retrieve value bases on access_token in servlet

                    - Raj

                      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!

                      Become a contributor for community

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

                      DigitalOcean Documentation

                      Full documentation for every DigitalOcean product.

                      Resources for startups and SMBs

                      The Wave has everything you need to know about building a business, from raising funding to marketing your product.

                      Get our newsletter

                      Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

                      New accounts only. By submitting your email you agree to our Privacy Policy

                      The developer cloud

                      Scale up as you grow — whether you're running one virtual machine or ten thousand.

                      Get started for free

                      Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

                      *This promotional offer applies to new accounts only.