// Tutorial //

Java JSON Example

Published on August 3, 2022
Default avatar
By Pankaj
Developer and author at DigitalOcean.
Java JSON Example

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.

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

	"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) {
		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();
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;
	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
		//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 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()) {
		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);

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

Download Java JSON Project

References: JSONLint - Great web tool to validate JSON data JSON Processing Reference Implementation JSR353 JCP Page

Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.

Sign up
About the authors
Default avatar


Developer and author at DigitalOcean.

Still looking for an answer?

Was this helpful?

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

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

    - Iris

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

      - Ariel

        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

          Great !

          - Rana

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

            - sai kiran

              Very helpful… keep it up… Thanks.

              - Biosync

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

                - sreenivas

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

                  - Joan

                    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