Java Write JSON Example - JSON Processing API

In this example, we will see how to write a JSON to a file with JSON-P library.
The code example is available at my Github repository.

JSON-P

JSON Processing (JSON-P) is a Java API to process (for e.g. parse, generate, transform and query) JSON messages. It produces and consumes JSON text in a streaming fashion (similar to StAX API for XML) and allows to build a Java object model for JSON text using API classes (similar to DOM API for XML).
Read more about JSON-P at official documentation - https://javaee.github.io/jsonp.

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) + "]";
    }
}

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();
The code example is available at my Github repository.

Comments