Java JSON Processing Tutorial

Java JSON processing tutorial shows how to use JSON-P library to work with JSON. 
The source code examples of this tutorial available on my GitHub repository.
JSR 353 addresses the standard Java API for JSON processing and shipped as part of JavaEE 7. Java API for JSON Processing (JSON-P) provides portable APIs to parse, generate, transform, and query JSON using object model and streaming APIs. 
There are two ways two work with JSON in JSON-P: streaming API and object model API.

Table of contents

  1. JSON-P Streaming API
  2. JSON-P Object model API
  3. Add Dependencies
  4. Java JSON Read Example
  5. Java JSON Write Example
  6. Java Create JSON Example
  7. Java Parse JSON Example
  8. Java JSON-P JsonObjectBuilder Example
  9. Java JSON-P JsonArrayBuilder Example
  10. JSON Pretty Printing Example

1. JSON-P Streaming API

The streaming API hands over parsing and generation control to the programmer. The streaming API provides an event-based parser and allows an application developer to ask for the next event rather than handling the event in a callback. This is called a pull method.
NameDescription
JsonContains static methods to create JSON parsers, generators, and their factories.
JsonParserRepresents an event-based parser reads JSON data from a stream.
JsonGeneratorWrites JSON data to a stream one value at a time.

2. JSON-P Object model API

The object model API creates a tree-like structure that represents the JSON data in memory. The tree can be flexibly navigated and queried. On the other hand, the object model API is often less efficient as the streaming model and requires more memory.
NameDescription
JsonContains static methods to create JSON parsers, generators, and their factories.
JsonObjectBuilderCreates an object model in memory by adding values from application code.
JsonArrayBuilderCreates an array model in memory by adding values from application code.
JsonReaderReads a JsonObject or a JsonArray from an input source.
JsonWriterWrites a JsonObject or a JsonArray to an output source.
The JsonValue, JsonObject, JsonArray, JsonString, and JsonNumber are JSON data types.

3. Add Dependencies

JSON-P is the reference implementation for Java JSON Processing API. We can use this in maven project by adding the following dependencies:
<dependency>
    <groupId>javax.json</groupId>
    <artifactId>javax.json-api</artifactId>
    <version>1.1</version>
</dependency>

<dependency>
    <groupId>org.glassfish</groupId>
    <artifactId>javax.json</artifactId>
    <version>1.1</version>
</dependency>
Let's create a JSON file named "posts.json":
{
    "id": 100,
    "title": "JSONP Tutorial",
    "description": "Post about JSONP",
     "content": "HTML content here",
    "tags": [
        "Java",
        "JSON"
    ]
}
We have Java bean classes that represent above JSON format as:
package net.javaguides.jsonp.tutorial;

import java.util.Arrays;

public class Post {
    private int id;
    private String title;
    private String description;
    private String content;
    private String[] tags;

    public Post() {

    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String[] getTags() {
        return tags;
    }

    public void setTags(String[] tags) {
        this.tags = tags;
    }

    @Override
    public String toString() {
        return "Post [id=" + id + ", title=" + title + ", description=" + description + ", content=" + content +
            ", tags=" + Arrays.toString(tags) + "]";
    }
}

4. Java JSON Read Example

In this example, we are reading "posts.json" file. We use JsonReader and JsonObject interfaces to read and extract fields and display.
Here is complete source code:
package net.javaguides.jsonp.tutorial;

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;

/**
 * Class to read json from a posts.json file.
 * @author Ramesh fadatare
 *
 */
public class ReadJSON {

    public static void main(String[] args) throws IOException {
        InputStream fis = new FileInputStream("posts.json");

        // create JsonReader object
        JsonReader jsonReader = Json.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 Post bean
        Post post = new Post();
        post.setId(jsonObject.getInt("id"));
        post.setTitle(jsonObject.getString("title"));
        post.setDescription(jsonObject.getString("description"));
        post.setContent(jsonObject.getString("content"));

        // reading arrays from json
        JsonArray jsonArray = jsonObject.getJsonArray("tags");
        String[] tags = new String[jsonArray.size()];
        int index = 0;
        for (JsonValue value: jsonArray) {
            tags[index++] = value.toString();
        }
        post.setTags(tags);
        // print post object
        System.out.println(post.toString());
    }
}
Output:
Post [id=100, title=JSONP Tutorial, description=Post about JSONP, 
content=HTML content here, tags=["Java", "JSON"]]

5. Java JSON Write Example

In this example, we write Post Java bean object into JSON file "posts.json". In the below example we use JsonGenerator.PRETTY_PRINTING configuration setting so we can set the writer for pretty printing.
package net.javaguides.jsonp.tutorial;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.json.Json;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import javax.json.JsonWriter;
import javax.json.JsonWriterFactory;
import javax.json.stream.JsonGenerator;


/**
 * Class to write json to a posts.json file.
 * @author Ramesh fadatare
 *
 */
public class WriteJSON {

    public static void main(String[] args) throws FileNotFoundException {
        Post post = createPost();

        JsonObjectBuilder postBuilder = Json.createObjectBuilder();
        JsonArrayBuilder tagsBuilder = Json.createArrayBuilder();

        for (String tag: post.getTags()) {
            tagsBuilder.add(tag);
        }

        postBuilder.add("id", post.getId())
            .add("title", post.getTitle())
            .add("description", post.getDescription())
            .add("content", post.getContent())
            .add("tags", tagsBuilder);


        JsonObject postJsonObject = postBuilder.build();

        System.out.println("Post JSON String -> " + postJsonObject);

        //write to file
        OutputStream os = new FileOutputStream("posts.json");
        JsonWriter jsonWriter = Json.createWriter(os);

        Map < String, Boolean > config = new HashMap < String, Boolean > ();
        config.put(JsonGenerator.PRETTY_PRINTING, true);

        JsonWriterFactory factory = Json.createWriterFactory(config);
        jsonWriter = factory.createWriter(os);

        jsonWriter.writeObject(postJsonObject);
        jsonWriter.close();
    }

    private static Post createPost() {
        // create a post
        Post post = new Post();
        post.setTitle("JSONP Tutorial");
        post.setId(100);
        post.setDescription("Post about JSONP");
        post.setContent("HTML content here");

        String[] tags = {
            "Java",
            "JSON"
        };
        // create some predefined tags
        post.setTags(tags);

        // set tags to post
        return post;
    }
}
Let's understand above Java JSON write an example.
The main JSON-P entry point is the Json class. It provides all the necessary methods to parse and build JSON strings from Java. Json is a singleton containing static factory methods for all relevant elements of the JSON-P API.
JsonObjectBuilder postBuilder = Json.createObjectBuilder();
JsonArrayBuilder tagsBuilder = Json.createArrayBuilder();
We created a Json object as:
postBuilder.add("id", post.getId())
.add("title", post.getTitle())
.add("description", post.getDescription())
.add("content", post.getContent())
.add("tags", tagsBuilder);
JsonObject postJsonObject = postBuilder.build();
Writing above created to "posts.json" file and print pretty with JsonGenerator.PRETTY_PRINTING setting:
//write to file
OutputStream os = new FileOutputStream("posts.json");
JsonWriter jsonWriter = Json.createWriter(os);

Map<String, Boolean> config = new HashMap<String, Boolean>();
config.put(JsonGenerator.PRETTY_PRINTING, true);

JsonWriterFactory factory = Json.createWriterFactory(config);
jsonWriter = factory.createWriter(os);

jsonWriter.writeObject(postJsonObject);
jsonWriter.close();

6. Java Create JSON Example

In the below example, JsonGenerator writes JSON data to an output source in a streaming way. The JsonGeneratorFactory contains methods to create JsonGenerator instances.
package net.javaguides.jsonp.tutorial;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

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


/**
 * Class to create a json using jsonp library.
 * @author Ramesh fadatare
 *
 */
public class CreateJSON {
    public static void main(String[] args) throws FileNotFoundException {
        OutputStream fos = new FileOutputStream("posts.json");

        Map < String, Boolean > config = new HashMap < String, Boolean > ();
        config.put(JsonGenerator.PRETTY_PRINTING, true);

        JsonGeneratorFactory factory = Json.createGeneratorFactory(config);

        JsonGenerator jsonGenerator = factory.createGenerator(fos);

        Post post = createPost();
        jsonGenerator.writeStartObject(); // {
        jsonGenerator.write("id", post.getId()); // "id":123
        jsonGenerator.write("title", post.getTitle());
        jsonGenerator.write("description", post.getDescription());
        jsonGenerator.write("content", post.getContent());

        jsonGenerator.writeStartArray("tags");
        for (String tag: post.getTags()) {
            jsonGenerator.write(tag);
        }

        jsonGenerator.writeEnd(); // end of phone num array
        jsonGenerator.writeEnd(); // }

        jsonGenerator.close();
    }

    private static Post createPost() {
        // create a post
        Post post = new Post();
        post.setTitle("JSONP Tutorial");
        post.setId(100);
        post.setDescription("Post about JSONP");
        post.setContent("HTML content here");

        String[] tags = {
            "Java",
            "JSON"
        };
        // create some predefined tags
        post.setTags(tags);

        // set tags to post
        return post;
    }
}
Let's understand the above Java create JSON example using JSON-P library.
We create a JSON and store in "posts.json" file:
OutputStream fos = new FileOutputStream("posts.json");
A JsonGenerator is created with a JsonGeneratorFactory. The factory receives configuration data which enable pretty printing:
Map<String, Boolean> config = new HashMap<String, Boolean>();
config.put(JsonGenerator.PRETTY_PRINTING, true);

JsonGeneratorFactory factory = Json.createGeneratorFactory(config);

JsonGenerator jsonGenerator = factory.createGenerator(fos);
``
An object is started with writeStartObject(). It is later ended with writeEnd():
```java
jsonGenerator.writeStartObject();
An array is started with writeStartArray(). It is later ended with writeEnd():
jsonGenerator.writeStartArray("tags");
Convert post object into Json object:
Post post = createPost();
jsonGenerator.writeStartObject(); // {
jsonGenerator.write("id", post.getId()); // "id":123
jsonGenerator.write("title", post.getTitle());
jsonGenerator.write("description", post.getDescription());
jsonGenerator.write("content", post.getContent());

private static Post createPost() {
		// create a post
        Post post = new Post();
        post.setTitle("JSONP Tutorial");
        post.setId(100);
        post.setDescription("Post about JSONP");
        post.setContent("HTML content here");

        String[] tags = {"Java", "JSON"};
        // create some predefined tags
        post.setTags(tags);
        
        // set tags to post
		return post;		
	}

7. Java Parse JSON Example

JsonParser parses JSON using the pull parsing programming model. In this model, the client code controls the thread and calls the method next() to advance the parser to the next state after processing each element.
The parser generates one of the following events: START_OBJECT, END_OBJECT, START_ARRAY, END_ARRAY, KEY_NAME, VALUE_STRING, VALUE_NUMBER, VALUE_TRUE, VALUE_FALSE, and VALUE_NULL.
Let's create a simple json inside a file named "posts.json".
[
	{
		"id": 100,
		"title": "JSONP Tutorial",
		"description": "Post about JSONP",
		"content": "HTML content here",
		"tags": [
			"Java",
			"JSON"
		]
	},
	{
		"id": 101,
		"title": "GSON Tutorial",
		"description": "Post about GSON",
		"content": "HTML content here",
		"tags": [
			"Java",
			"JSON"
		]
	},
	{
		"id": 102,
		"title": "Simple JSON Tutorial",
		"description": "Post about Simple JSON",
		"content": "HTML content here",
		"tags": [
			"Java",
			"JSON"
		]
	}
]
In the example, we parse the above posts.json file using the JSON-P streaming API.
package net.javaguides.jsonp.tutorial;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

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


/**
 * Class to parse a json using jsonp.
 * @author Ramesh fadatare
 *
 */

public class ParseJSON {

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

        InputStream is = new FileInputStream("posts.json");

        JsonParserFactory factory = Json.createParserFactory(null);
        JsonParser parser = factory.createParser(is, StandardCharsets.UTF_8);

        if (!parser.hasNext() && parser.next() != JsonParser.Event.START_ARRAY) {
            return;
        }

        // looping over object attributes
        while (parser.hasNext()) {

            Event event = parser.next();

            // starting object
            if (event == JsonParser.Event.START_OBJECT) {

                while (parser.hasNext()) {

                    event = parser.next();

                    if (event == JsonParser.Event.KEY_NAME) {

                        String key = parser.getString();

                        switch (key) {

                            case "id":
                                parser.next();

                                System.out.printf("id: %s%n", parser.getString());
                                break;

                            case "title":
                                parser.next();

                                System.out.printf("title: %s%n", parser.getString());
                                break;

                            case "description":
                                parser.next();

                                System.out.printf("description: %s%n%n", parser.getString());
                                break;

                            case "content":
                                parser.next();

                                System.out.printf("content: %s%n%n", parser.getString());
                                break;
                        }
                    }
                }
            }
        }
    }
}
Output:
id: 100
title: JSONP Tutorial
description: Post about JSONP
content: HTML content here

id: 101
title: GSON Tutorial
description: Post about GSON
content: HTML content here

id: 102
title: Simple JSON Tutorial
description: Post about Simple JSON
content: HTML content here
A JsonParser is created from JsonParserFactory:
InputStream is = new FileInputStream("posts.json");

JsonParserFactory factory = Json.createParserFactory(null);
JsonParser parser = factory.createParser(is, StandardCharsets.UTF_8);
First, we pass the beginning of the array:
if (!parser.hasNext() && parser.next() != JsonParser.Event.START_ARRAY) {

    return;
}
Then we go through the array in a while loop. The parser hasNext() method returns false when we reach the end of the array. We pull the next parsing event with next():
// looping over object attributes
while (parser.hasNext()) {

    Event event = parser.next();

    // starting object
    if (event == JsonParser.Event.START_OBJECT) {
...     
In another while loop, we go through the keys of the current object:
while (parser.hasNext()) {

    event = parser.next();

    if (event == JsonParser.Event.KEY_NAME) {
...
In the switch statement we check for the key name and get its value with getString():
String key = parser.getString();

switch (key) {

    case "name":
        parser.next();

        System.out.printf("Name: %s%n", parser.getString());
        break;
...  

8. Java JSON-P JsonObjectBuilder Example

package net.javaguides.jsonp.examples;

import java.io.StringWriter;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;

import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import javax.json.JsonWriter;
import javax.json.JsonWriterFactory;
import javax.json.stream.JsonGenerator;

/**
 * The class demonstrates the usage of JsonObjectBuilder class
 * @author Ramesh Fadatare
 *
 */
public class JsonObjectBuilderExample {
    public static void main(String[] args) {
        String postedDate = LocalDate.of(2019, 7, 15).toString();

        JsonObjectBuilder jsonObjectBuilder = Json.createObjectBuilder()
            .add("id", "100")
            .add("title", "JSON-Processing API Post")
            .add("description", "JSON-Processing API Post")
            .add("postedDate", postedDate);

        JsonObject jsonObject = jsonObjectBuilder.build();


        Map < String, Boolean > config = new HashMap < String, Boolean > ();
        config.put(JsonGenerator.PRETTY_PRINTING, true);

        JsonWriterFactory jwf = Json.createWriterFactory(config);
        StringWriter sw = new StringWriter();

        try (JsonWriter jsonWriter = jwf.createWriter(sw)) {
            jsonWriter.writeObject(jsonObject);
            System.out.println(sw);
        }
    }
}
Output:

{
    "id": "100",
    "title": "JSON-Processing API Post",
    "description": "JSON-Processing API Post",
    "postedDate": "2019-07-15"
}
Let's understand the above example.
A JsonObjectBuilder is created with createObjectBuilder(). New pairs are inserted with add(). Finally, the JsonObject is created with build():
String postedDate = LocalDate.of(2019, 7, 15).toString();

JsonObjectBuilder jsonObjectBuilder = Json.createObjectBuilder()
		.add("id", "100")
		.add("title", "JSON-Processing API Post")
		.add("description", "JSON-Processing API Post")
		.add("postedDate", postedDate);

JsonObject jsonObject = jsonObjectBuilder.build();
Create JsonWriterFactory from createWriterFactory() method and pretty-print the JSON with JsonGenerator.PRETTY_PRINTING settings:
Map<String, Boolean> config = new HashMap<String, Boolean>();
config.put(JsonGenerator.PRETTY_PRINTING, true);

JsonWriterFactory jwf = Json.createWriterFactory(config);
StringWriter sw = new StringWriter();

try (JsonWriter jsonWriter = jwf.createWriter(sw)) {
	jsonWriter.writeObject(jsonObject);
	System.out.println(sw);
}

9. Java JSON-P JsonArrayBuilder Example

In this example, we create a list of post objects and transform them into a JsonArray and we write this JSON to console.
package net.javaguides.jsonp.examples;

import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObject;
import javax.json.JsonWriter;
import javax.json.JsonWriterFactory;
import javax.json.stream.JsonGenerator;

import net.javaguides.jsonp.tutorial.Post;

/**
 * The class to demonstrate the usage of JsonArrayBuilder interface.
 * @author Ramesh Fadatare
 *
 */
public class JsonArrayBuilderExample {
    public static void main(String[] args) {

        JsonArrayBuilder jsonArrayBuilder = Json.createArrayBuilder();

        List < Post > posts = createPosts();

        posts.forEach(post - > {

            JsonObject json = Json.createObjectBuilder()
            .add("id", post.getId())
            .add("title", post.getTitle())
            .add("description", post.getDescription())
            .add("content", post.getContent()).build();

            jsonArrayBuilder.add(json);
        });


        JsonArray jsonArray = jsonArrayBuilder.build();

        Map < String, Boolean > config = new HashMap < String, Boolean > ();
        config.put(JsonGenerator.PRETTY_PRINTING, true);

        JsonWriterFactory jwf = Json.createWriterFactory(config);
        StringWriter sw = new StringWriter();

        try (JsonWriter jsonWriter = jwf.createWriter(sw)) {

            jsonWriter.writeArray(jsonArray);

            System.out.println(sw);
        }
    }

    public static List < Post > createPosts() {

        List < Post > posts = new ArrayList < > ();
        // create a post
        Post post = new Post();
        post.setTitle("JSONP Tutorial");
        post.setId(100);
        post.setDescription("Post about JSONP");
        post.setContent("HTML content here");

        String[] tags = {
            "Java",
            "JSON"
        };
        // create some predefined tags
        post.setTags(tags);


        // create a post
        Post post1 = new Post();
        post1.setTitle("Jackson Tutorial");
        post1.setId(100);
        post1.setDescription("Post about Jackson API");
        post1.setContent("HTML content here");
        // create some predefined tags
        post1.setTags(new String[] {
            "Java",
            "JSON",
            "Jackson"
        });

        // create a post
        Post post2 = new Post();
        post2.setTitle("Google Gson Tutorial");
        post2.setId(100);
        post2.setDescription("Post about Google Gson");
        post2.setContent("HTML content here");

        // create some predefined tags
        post2.setTags(new String[] {
            "Java",
            "JSON",
            "Gson"
        });

        posts.add(post);
        posts.add(post1);
        posts.add(post2);
        return posts;
    }
}
Output:

[
    {
        "id": 100,
        "title": "JSONP Tutorial",
        "description": "Post about JSONP",
        "content": "HTML content here"
    },
    {
        "id": 100,
        "title": "Jackson Tutorial",
        "description": "Post about Jackson API",
        "content": "HTML content here"
    },
    {
        "id": 100,
        "title": "Google Gson Tutorial",
        "description": "Post about Google Gson",
        "content": "HTML content here"
    }
]
Let's understand the above example.
A JsonArrayBuilder is created with createArrayBuilder():
JsonArrayBuilder jsonArrayBuilder = Json.createArrayBuilder();
In this for loop, we create JSON objects and add them to the builder:
posts.forEach(post -> {

	JsonObject json = Json.createObjectBuilder()
			.add("id", post.getId())
			.add("title", post.getTitle())
			.add("description", post.getDescription())
			.add("content", post.getContent()).build();

	jsonArrayBuilder.add(json);
});
The build() method creates a JsonArray from the builder:
JsonArray jsonArray = jsonArrayBuilder.build();
The JsonArray is written to the writer:
jsonWriter.writeArray(jsonArray);

10. JSON Pretty Printing Example

With JsonGenerator.PRETTY_PRINTING configuration setting, we can set the writer for pretty printing. In the example, we create a JSON object and print it to the console. The output is pretty-printed.
package net.javaguides.jsonp.examples;

import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonWriter;
import javax.json.JsonWriterFactory;
import javax.json.stream.JsonGenerator;
import java.io.StringWriter;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;

public class JsonPrettyPrintExample {
    public static void main(String[] args) {

        String postedDate = LocalDate.of(2019, 7, 15).toString();

        JsonObject json = Json.createObjectBuilder()
            .add("id", "100")
            .add("title", "JSON-Processing API Post")
            .add("description", "JSON-Processing API Post")
            .add("postedDate", postedDate).build();

        Map < String, Boolean > config = new HashMap < String, Boolean > ();
        config.put(JsonGenerator.PRETTY_PRINTING, true);

        JsonWriterFactory jwf = Json.createWriterFactory(config);
        StringWriter sw = new StringWriter();

        try (JsonWriter jsonWriter = jwf.createWriter(sw)) {
            jsonWriter.writeObject(json);
            System.out.println(sw.toString());
        }
    }
}
Output:

{
    "id": "100",
    "title": "JSON-Processing API Post",
    "description": "JSON-Processing API Post",
    "postedDate": "2019-07-15"
}
Let's understand the above example.
Created a simple JSON object:
JsonObject json = Json.createObjectBuilder()
.add("id", "100")
.add("title", "JSON-Processing API Post")
.add("description", "JSON-Processing API Post")
.add("postedDate", postedDate).build();
The configuration file is passed to the JsonWriterFactory and use JsonWriter to write JSON to console:
Map<String, Boolean> config = new HashMap<String, Boolean>();
config.put(JsonGenerator.PRETTY_PRINTING, true);

JsonWriterFactory jwf = Json.createWriterFactory(config);
StringWriter sw = new StringWriter();

try (JsonWriter jsonWriter = jwf.createWriter(sw)) {
	jsonWriter.writeObject(json);
	System.out.println(sw.toString());
}

Reference

The source code examples of this tutorial available on my GitHub repository.

Comments

  1. Do you have an example which parses the json string or json object into Java Object ?

    ReplyDelete
    Replies
    1. https://www.javaguides.net/2019/04/jackson-convert-java-object-tofrom-json-example.html

      Delete

Post a Comment