Preparing for Java and Spring Boot Interview?

Join my Newsletter, its FREE

Wednesday, March 30, 2022

How to Read JSON String in Java using json-simple library? Example Tutorial

Hello guys, if you are wondering how to read JSON in Java using the json-simple library and looking for an example then you have come to the right place. Earlier, I have shown you how to parse JSON using Jackson and how to read JSON using the Gson library in Java, and today, I am going to share how to read JSON strings using json-simple, another popular JSON library in Java. If you don't know, JSON is a text format that is widely used as a data-interchange language because its parsing and its generation are easy for programs. It is slowly replacing XML as the most powerful data interchange format, as it is lightweight, consumes less bandwidth, and is also platform-independent.  

Though Java doesn't have built-in support for parsing JSON files and objects, there are a lot of good open-source JSON libraries are available which can help you to read and write JSON objects to files and URLs. Two of the most popular JSON parsing libraries are Jackson and Gson. They are mature, rich, and stable.

Though there are a couple of more libraries there like JSON simple, which we are going to use in this example. Jackson and Gson later do a very nice job in mapping JSON objects and serialization. JSON is also used in requests and responses between client-server communication.

In this tutorial, we are going to see how to read and write JSON to file using JSON.Simple library, and you will notice how simple working with JSON is.

Since we don't have JSON support in JDK, we need to download this open-source library. If you are using maven to download the JAR and manage dependency, if not then you should, then you can just include the following dependencies in your pom.xml file :

    <artifactid> json-simple</artifactid>

Otherwise, you have to add the newest version of json-simple-1.1.1.jar in CLASSPATH of your Java program. Also, Java 9 is coming up with built-in JSON support in JDK, which will make it easier to deal with JSON format, but that will not replace the existing Jackson and GSON library, which seems to be very rich with functionality.

How to create JSON File in Java? Example Tutorial

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 encoding and decoding JSON text. 

 It is fully compliant with JSON specifications (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 the streaming output of JSON text.

In this example, we have two methods for reading and writing JSON. JSONParser parses a JSON file and returns a JSON object.

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

Once you receive the array, you can use the Iterator to traverse through the JSON array. This way you can retrieve each element of JSONArray in Java. Now, let's see how we can write JSON String to a file. 

How to read and write JSON String in Java using json-simple

Again we first need to create a JSONObject instance, then we can put data by entering the key and value. If you have not noticed the similarity then let me tell you, JSONObject is just like Map while JSONArray is like List.

You can see code in your write method, that we are using the put() method to insert value in JSONObject and using add() method to put the value inside the JSONArray 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 a file by calling toJSONString() method in JSONObject and using a FileWriter to write that String to the file.

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

        // let's read
     * 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(" " +;

        } catch (Exception ex) {
     * 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();

        json.put("characters", jsonArray);

        try {
            System.out.println("Writting JSON into file ...");
            FileWriter jsonFileWriter = new FileWriter(file);

        } catch (IOException e) {


Writting JSON into file ...
{"author":"J. K. Rolling","title":"Harry Potter and Half Blood Prince",
Reading JSON file from Java program
title: Harry Potter and Half Blood Prince
author: J. K. Rolling
price: 20

That's all about how to parse JSON String in a 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.

Other JSON tutorials you may like to explore
  • How to convert a JSON  String to POJO in Java? (tutorial)
  • 3 Ways to parse JSON String in Java? (tutorial)
  • How to convert a JSON array to a String array in Java? (example)
  • How to convert a Map to JSON in Java? (tutorial)
  • How to use Google Protocol Buffer in Java? (tutorial)
  • How to use Gson to convert JSON to Java Object? (example)
  • 5 Books to Learn REST and RESTful Web Services (books)
  • How to load CSV files with headers using Jackson in Java? (CSV example)
  • How to parse JSON with the date field using Jackson? (example)
  • 3 ways to ignore null fields in Java using Jackson? (example)

P.S. - If you want to learn how to develop RESTful Web Services using Spring Framework, check out Eugen Paraschiv's REST with Spring course. He has recently launched the certification version of the course, which is full of exercises and examples to further cement the real-world concepts you will learn from the course.


Anonymous said...

Why you think JSON is better than XML? In my opinion XML has more tools available than JSON e.g. XPath, XSLT and XQueyr.

Anonymous said...

When you convert a JSON String to Java Object, does libraries also take care of encoding? I am new to JSON and don't know if it contains encoding anywhere in header just like XML does. Any idea?

Kelvin said...

Oracle has proposed to drop lightweight JSON API from Java 9 in favor of two other features, value type and generics over primitive types. This is what Oracle's head of Java Mark has to say

“We may reconsider this [JSON API] JEP for JDK 10 or a later release, especially if new language features such as value types and generics over primitive types (JEP 218) enable a more compact and expressive API.” – Mark Reinhold

Unknown said...

i have a txt file like

accept reply: true
ASC,"This is some text that
gets to the next line
and the next line and possibly any number of lines."
ASC,"More text"

accept reply: false

accept reply: false

accept reply: true
float, 4.6,9.3

bool, false

this file convert into json formate how can i do. json formate like this

[{"header":{"stream":2,"function":3,"reply":true},"body":[{"format":"A","value":"This is some text that\ngets to the next line\n and the next line and possibly any number of lines."},[{"format":"U4","value":6},{"format":"Boolean","value":true},{"format":"F4","value":5.21}],[{"format":"A","value":"More text"},[{"format":"U4","value":8}]]]},{"header":{"stream":10,"function":11,"reply":false},"body":{"format":"A","value":"test2"}},{"header":{"stream":9,"function":1,"reply":false},"body":[]},{"header":{"stream":1,"function":15,"reply":true},"body":[{"format":"Boolean","value":[true,false,true,true,false]},{"format":"U4","value":[3,5,6,3,7,2,6]},{"format":"F4","value":9},[{"format":"U4","value":4},[{"format":"F4","value":[4.6,9.3]},{"format":"Boolean","value":false}],[[[{"format":"U4","value":5},[]]],[{"format":"A","value":"test3"},{"format":"A","value":"test\n4"},[]]]]]}]

please help
thank you

Anonymous said...

I am getting compile time error "Cannot cast from Object to long" at line long price = (long) json.get("price");

It should be like :long price = (Long) json.get("price");

Unknown said...

What I have noticed is that you cannot retrieve an int value. But long is possible.

Anonymous said...

want to get values from jSON file.facing some errors.I dont want to use "parse".
Using JSONObject obj=new JSONObject();
or using JSONArray

Anonymous said...

I am getting error as "org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject" inside readJSON method.

Earliest help would be much appreciated.

Anonymous said...

how can we convert a json object to in a string object

Anonymous said...

just put.asString();

Unknown said...

{"Status":"1","Error":"-","Data": "test data"}

i want to convert this json formate into java please help

Post a Comment