How to Read JSON String in Java - Json-Simple Example

JSON is a text format is a widely used as data-interchange language because its parsing and its generation is easy for programs. It is slowly replacing XML as most powerful data interchange format, as it is lightweight, consumes less bandwidth and also platform independent.  Though Java doesn't have built in support for parsing JSON files and objects, there are lot of good open source JSON libraries are available which can help you to read and write JSON object to file and URL. Two of the most popular JSON parsing libraries are Jackson and Gson. They are matured, rich and stable. Though there are couple of more libraries there like JSON simple, which we are going to use in this example. Between Jackson and Gson, later does very nice job in mapping JSON object and serialization. JSON is also used in request and response 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 yourself 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 JAR and managing dependency, if not then you should, then you can just include 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 existing Jackson and GSON library, which seems to be very rich with functionality.

How to create JSON File in Java

How to read and write JSON String in JAva
Here is step by step guide on how to create 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 functionality 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 attribute, but you need to remember it to type cast in String or JSONArray depending upon what you are receiving. Once you receive the array, you can use Iterator to traverse through 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. 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, JSONObject is just like Map while JSONArray is like List. You can see code in your write method, that we are using put() method to insert value in JSONObject and using add() method to put value inside JSONArray object. Also note, array is used to create nested structure in JSON. Once your JSON String is ready, you can write that JSON String to file by calling toJSONString() method in JSONObject and using a FileWriter to write that String to 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","price":20,"characters":["Harry","Ron","Hermione"]}
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 Java program. You can also use other popular library like Gson or Jackson to do the same task. I like JSON simple library to start with because it's really simple, and it provide direct mapping between Java classes and JSON variables. For example, String in Java also map 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 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.

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


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");

Francis Nduba Numbi said...

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

Post a Comment