How to read and write JSON String in JAva

Here is a step by step guide on how to create a JSON file in Java and how to read and write on that. In this tutorial we are going to use JSON Simple open-source library, JSON.simple is a simple Java toolkit for JSON for to encoding and decoding JSON text.  It is fully compliant with JSON specification (RFC4627) . It provides multiple functionalities such as reading, writing, parsing, escape JSON text while keeping the library lightweight. It is also flexible, simple, and easy to use by reusing Map and List interfaces. JSON.Simple also supports streaming output of JSON text. In this example, we have two methods for reading and writing JSON. JSONParser  parse a JSON file and return a JSON object.

Once you get JSONObject, you can get individual fields by calling get() method and passing name of the attribute, but you need to remember it to typecast in String or JSON Array depending upon what you are receiving.

Once you receive the array, you can use the Iterator to traverse through JSON array. This way you can retrieve each element of JSON Array in Java. Now, let’s see how we can write JSON String to a file. Again we first need to create a JSONObject instance, then we can put data by entering key and value. If you have not noticed the similarity then let me tell you, JSON Object is just like Map while JSON Array is like List.

You can see code in your write method, that we are using put() method to insert value in JSON Object and using add() method to put the value inside JSON Array object. Also note, the array is used to create a nested structure in JSON. Once your JSON String is ready, you can write that JSON String to file by calling to JSON String() method in JSON Object and using a File Writer to write that String to file.

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

/**
 * Java Program to show how to work with JSON in Java.
 * In this tutorial, we will learn creating
 * a JSON file, writing data into it and then reading from JSON file.
 *
 * @author Javin Paul
 */
public class JSONDemo{

    public static void main(String args[]) {

        // generate JSON String in Java
        writeJson("book.json");

        // let's read
        readJson("book.json");
    }
    /*
     * Java Method to read JSON From File
     */
    public static void readJson(String file) {
        JSONParser parser = new JSONParser();

        try {
            System.out.println("Reading JSON file from Java program");
            FileReader fileReader = new FileReader(file);
            JSONObject json = (JSONObject) parser.parse(fileReader);

            String title = (String) json.get("title");
            String author = (String) json.get("author");
            long price = (long) json.get("price");

            System.out.println("title: " + title);
            System.out.println("author: " + author);
            System.out.println("price: " + price);

            JSONArray characters = (JSONArray) json.get("characters");
            Iterator i = characters.iterator();

            System.out.println("characters: ");
            while (i.hasNext()) {
                System.out.println(" " + i.next());
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    /*
     * Java Method to write JSON String to file
     */
    public static void writeJson(String file) {
        JSONObject json = new JSONObject();
        json.put("title", "Harry Potter and Half Blood Prince");
        json.put("author", "J. K. Rolling");
        json.put("price", 20);

        JSONArray jsonArray = new JSONArray();
        jsonArray.add("Harry");
        jsonArray.add("Ron");
        jsonArray.add("Hermoinee");

        json.put("characters", jsonArray);

        try {
            System.out.println("Writting JSON into file ...");
            System.out.println(json);
            FileWriter jsonFileWriter = new FileWriter(file);
            jsonFileWriter.write(json.toJSONString());
            jsonFileWriter.flush();
            jsonFileWriter.close();
            System.out.println("Done");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

Output:
Writting JSON into file ...
{"author":"J. K. Rolling","title":"Harry Potter and Half Blood Prince",
"price":20,"characters":["Harry","Ron","Hermione"]}
Done
Reading JSON file from Java program
title: Harry Potter and Half Blood Prince
author: J. K. Rolling
price: 20
characters:
 Harry
Ron
Hermione

That’s all about how to parse JSON String in Java program. You can also use other popular libraries like Gson or Jackson to do the same task. I like the JSON simple library to start with because it’s really simple, and it provides a direct mapping between Java classes and JSON variables.

For example, String in Java also maps to string in JSON, java.lang.Number maps to number in JSON, and boolean maps to true and false in JSON, and as I have already said object is Map and array is List in Java.

All I can say is JSON is already a big thing and in the coming days every Java programmer is going to write more and more code to parse or encode decode JSON String, it’s better to start early and learn how to deal with JSON in Java.