JSON.simple example – Read and write JSON

JSON.simple is a simple Java library for JSON processing, read and write JSON data and full compliance with JSON specification (RFC4627).

Note
Alternatively, you should consider Jackson 2 or Gson

In this tutorial, we show you how to use JSON.simple to read and write JSON data from / to a file.

1. JSON.simple Dependency

JSON.simple is available at Maven central repository.

pom.xml

        <dependency>
            <groupId>com.googlecode.json-simple</groupId>
            <artifactId>json-simple</artifactId>
            <version>1.1.1</version>
        </dependency>

2. Write JSON to file

In below example, it writes JSON data via JSONObject and JSONArray, and save it into a file named “f:\\test.json”.

JsonSimpleWriteExample.java

package com.mkyong;

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

import java.io.FileWriter;
import java.io.IOException;

public class JsonSimpleWriteExample {

    public static void main(String[] args) {

        JSONObject obj = new JSONObject();
        obj.put("name", "mkyong.com");
        obj.put("age", new Integer(100));

        JSONArray list = new JSONArray();
        list.add("msg 1");
        list.add("msg 2");
        list.add("msg 3");

        obj.put("messages", list);

        try (FileWriter file = new FileWriter("f:\\test.json")) {

            file.write(obj.toJSONString());
            file.flush();

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

        System.out.print(obj);

    }

}

Output

f:\\test.json

{
	"age":100,
	"name":"mkyong.com",
	"messages":["msg 1","msg 2","msg 3"]
}

3. Read JSON from file

Use JSONParser to read above generated JSON file “f:\\test.json”, and display each of the values.

JsonSimpleReadExample.java

package com.mkyong;

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

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

public class JsonSimpleReadExample {

    public static void main(String[] args) {

        JSONParser parser = new JSONParser();

        try {

            Object obj = parser.parse(new FileReader("f:\\test.json"));

            JSONObject jsonObject = (JSONObject) obj;
            System.out.println(jsonObject);

            String name = (String) jsonObject.get("name");
            System.out.println(name);

            long age = (Long) jsonObject.get("age");
            System.out.println(age);

            // loop array
            JSONArray msg = (JSONArray) jsonObject.get("messages");
            Iterator<String> iterator = msg.iterator();
            while (iterator.hasNext()) {
                System.out.println(iterator.next());
            }

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

    }

}

Output


{"name":"mkyong.com","messages":["msg 1","msg 2","msg 3"],"age":100}
mkyong.com
100
msg 1
msg 2
msg 3

References

  1. JSON.simple official website
  2. JSON.simple encoding JSON example
  3. JSON.simple decoding JSON example

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
Subhrajit Bhattacharya
Guest
Subhrajit Bhattacharya

mkyong. Just wanted to say thanks for your articles. They are simple and clear, and they have benefited me very much.

Alexandre luz
Guest
Alexandre luz

I did exactly how you did in the code up here, but I keep getting this error:

Unexpected character (?) at position 0.

at org.json.simple.parser.Yylex.yylex(Yylex.java:610)

at org.json.simple.parser.JSONParser.nextToken(JSONParser.java:269)

at org.json.simple.parser.JSONParser.parse(JSONParser.java:118)

at org.json.simple.parser.JSONParser.parse(JSONParser.java:92)

swati singh
Guest
swati singh

JSONArray list = new JSONArray();

list.add(“msg 1”);

list.add(“msg 2”);

list.add(“msg 3”);

Error: The Method add(String) is undefined for the type JSONArray

What will be the solution please help

bougueddach
Guest
bougueddach

make sure you’ve imported org.json.simple.JSONArray and not org.json.JSONArray

bohan
Guest
bohan

Hi mkyong. Thank you for this json library!
One question, do you have a function in this library updating an existing json file in a directory?

Madhu Sudhan Baddam
Guest
Madhu Sudhan Baddam

How can i pass the folder path in the JSON.

But when passing the path(“/latest/object/300000006637803/child/child_c ) to JSON it reading as “/latest/MetaData_c/300000006637803/child/MetaDataFieldsCollection_c”

code:

part=new LinkedHashMap();
part.put(“id”,count);
part.put(“path”,”/latest/object/300000006637803/child/child_c);
part.put(“operation”,operation);
System.out.println(JSONValue.toJSONString(part));

output:

{

“id”:”part1″,

“path”:”/latest/MetaData_c/300000006637803/child/MetaDataFieldsCollection_c”,

“operation”:”create”

}

Mihir Monani
Guest
Mihir Monani

In your example (Number :-2 ) :- you added data in this sequence , Name -Age -Message. but it will print data in this sequence :- Age- Name- Message.

Any reason? how do you enforce storing sequence as data adding sequence??

beginnerstutorialexamples
Guest
beginnerstutorialexamples

Good explained example.

Visit beginnerstutorialexamples.com fore more java json tutorial with examples.

http://www.beginnerstutorialexamples.com/json-tutorial-for-beginners-with-examples/

nikhil
Guest
nikhil

consider i have Json file and i need to append more json data to it . how can i do it]

ajay
Guest
ajay

i am new to java…i want to parse the following json response in java ,please guide me..thanks in advance

{“devices”:{“002629032f38”:{“connectionStatus”:”online”,”descriptionXml”:””,”deviceClass”:{“classType”:”HD IR

amal
Guest
amal

very helpful really great and simple example

hutuwazi
Guest
hutuwazi

I guess you are a Chinese, shake hand. ;)

Majid Lotfi
Guest
Majid Lotfi
Hi, thanks for this tutorial, I would like a java code that generate this json structure : “agencies”: { “1”: { assignedAgencies: [ “agency1”, “agency2”, “agency5”], restOfAgencies: [ “agency3”, “agency4”, “agency6”] }, “2”: { assignedAgencies: [ “agency6”, “agency5”], restOfAgencies: [ “agency1”, “agency2”, “agency3”, “agency4”] } } Thank you, your help is appreciated.
DrNo
Guest
DrNo

Thank you for your support….I just need to know how to append pojos into the json file.The above example overwrites the data.Your help is always appreciable.

prasanth
Guest
prasanth

how can i get json array in highchart

Robson Carvalho
Guest
Robson Carvalho

Thank you!

Nathan Watts
Guest
Nathan Watts

getting this error:

Exception in thread “main” java.lang.NoClassDefFoundError: com/ibm/json/java/internal/SerializerVerbose

at com.bps.queuemanager.beans.QueueManagerBean.main(QueueManagerBean.java:16)

Caused by: java.lang.ClassNotFoundException: com.ibm.json.java.internal.SerializerVerbose

at java.net.URLClassLoader$1.run(Unknown Source)

at java.net.URLClassLoader$1.run(Unknown Source)

at java.security.AccessController.doPrivileged(Native Method)

at java.net.URLClassLoader.findClass(Unknown Source)

at java.lang.ClassLoader.loadClass(Unknown Source)

at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)

at java.lang.ClassLoader.loadClass(Unknown Source)

… 1 more

When creating the object:

public static void main(String argv[]) {

JSONObject obj = new JSONObject();

….

….

….

….

Ali Gajani
Guest
Ali Gajani

This doesn’t work when you have greater than 1 JSON ? How to do it recursively?

Michael Wiggins
Guest
Michael Wiggins

How you do anything else recursively; Use a loop.

Typically I’d use a for-loop where each record created is read from an array.

Dougal
Guest
Dougal

Great example thankyou.

Morgan
Guest
Morgan

Hey!
Really nice and easy tutorial, thanks a bunch :)

I have one problem though, when I read with the JSONParser, the java application keeps the file in use.
If one were using streams, you could close it, but I can’t find anything on how to “cut” the connection to the json file on the computer so I can delete, move or change its’ name.

Bryce Summers
Guest
Bryce Summers

For the following line in the reading example the word long should probably be capitalized:

long age = (Long) jsonObject.get(“age”);

Deepak Srivastav
Guest
Deepak Srivastav

long is a primitive type. We need to Cast the Object for long and it only happen with Long Class. This is similar as double to Double

ajit
Guest
ajit

Nice explanation :)

kanangkuan
Guest
kanangkuan

How can I write JSON with which there are multiple children e.g

{

“name” : “IR 1561-149-1”,

“gid” : “3660”,

“id”: “67”,

“layer”: “14”,

“location” : ” “,

“children” : [

{

“name” : “IR 1561-149”,

“gid” : “3563”,

“id”: “68”,

“method” : “true”,

“layer”: “15”,

“location” : ” “,

“children” : [

{

“name” : “IR 1561”,

“gid” : “2584”,

“id”: “69”,

“method” : “true”,

“layer”: “16”,

“location” : ” ”

}

]

}

]

}

Tian Zheng
Guest
Tian Zheng

I believe the best solution is to create a JSONArray that is called “children” with several “child” JSONObjects in it.

ajay
Guest
ajay

“devices”:{“002629032f38”:{“connectionStatus”:”online”,”descriptionXml”:””,”deviceClass”:{“classType”:”HD IR Bridge”,”classTypeId”:3},”deviceId”:”002629032f38″,”deviceName”:””,”deviceStateTable”:[{“allowedValueList”:null,”dataType”:”FLOAT”,”defaultValue”:””,”lowerRange”:0,”maximum”:0,”minimum”:0,”name”:”temperature”,”readOnly”:true,”sendEvents”:true,”stepSize”:0,”upperRange”:0,”value”:”22″}],”eventList”:[“temperature”],”properties”:{“friendlyName”:”irbridgemaster”,”location”:”default”,”tag”:”by+location”},”properties_readonly”:{“UDN”:”121-121-121-121″,”descripti

anil kumar
Guest
anil kumar
try { JSONParser parsera = new JSONParser(); Object obj1 = parsera.parse(yourJsonString); JSONObject jsonObject = (JSONObject) obj1; Object obj2=parsera.parse((String) jsonObject.get(“children”)); if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) { JSONArray jsonArray1=new JSONArray((JSONObject)obj2); for (int i = 0; i < jsonArray1.length(); i++) { org.json.JSONObject c1 = jsonArray1.getJSONObject(i); Object obj3=parsera.parse((String) c1.get("children")); JSONArray jsonArray2=new JSONArray((JSONObject)obj2); for (int j = 0; j < jsonArray2.length(); j++) { org.json.JSONObject c2 = jsonArray2.getJSONObject(j); //Now you can read third child object values from object c2 } } } } catch (Exception e) { }
aga
Guest
aga

this same process of reading and writing from/to JSON applies to Blackberry application OS 7 as well?
Thank you in advance

Kishore
Guest
Kishore

error at
msg.iterator();

bidhu
Guest
bidhu

What is the need of that .xml code.
Can any one plz explain me.

Shero
Guest
Shero

Try reading? Dumbass.

Nick
Guest
Nick

Name calling is quite unnecessary on a programming forum, isn’t it. You sound like a schoolyard bully.

a
Guest
a

ddd

Abhishek
Guest
Abhishek

how to handle multiple json objects present in a file ? something like this

[{“NAME”:”Alan”,”VALUE”:12,”COLOR”:”blue”,”DATE”:”Sep. 25, 2009″},
{“NAME”:”Shan”,”VALUE”:13,”COLOR”:”green\tblue”,”DATE”:”Sep. 27, 2009″},
{“NAME”:”John”,”VALUE”:45,”COLOR”:”orange”,”DATE”:”Sep. 29, 2009″},
{“NAME”:”Minna”,”VALUE”:27,”COLOR”:”teal”,”DATE”:”Sep. 30, 2009″}]

How to parse such json file with this library.

Abhishek
Guest
Abhishek

OK i figured it out. It’s pretty simple

JSONArray jsonarray = (JSONArray)obj;

for (int i=0; i<jsonarray.size(); i++) {

JSONObject jsonObject= (JSONObject)jsonarray.get(i);
String name = (String) jsonObject.get("name");
System.out.println(name);
long age = (Long) jsonObject.get("age");
System.out.println(age);

// loop array
JSONArray msg = (JSONArray) jsonObject.get("messages");
Iterator iterator = msg.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}

}

Maks
Guest
Maks

Hello,
I have a question. Shouldn’t be the FileReader closed too? The same way as a FileWriter instance in example above?

Manuaran
Guest
Manuaran

here is the answer.

JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader(“/Users//Documents/file1.txt”));

codegirl
Guest
codegirl

are you trying to answer me?

codegirl
Guest
codegirl
this is a great example! thank you. I am using the principals in this tutorial and am getting warnings when I try to put a K,V pair in to a newly created JSONObject. JSONObject jsonDevice = new JSONObject(); jsonDevice.put(“dbVersion”, “2”); This causes the following warning: “Type safety: The method put(Object, Object) belongs to the raw type HashMap. References to generic type HashMap should be parameterized” But if I parameterize it to be JSONObject it throws a compile error. ” – The type JSONObject is not generic; it cannot be parameterized with arguments – The type JSONObject is not generic; it… Read more »
codegirl
Guest
codegirl

oh yeah, I checked StackOverflow and it seems from this thread that this is an issue with JSON because although it extends HashMap, it does so without generics so you can’t parameterize the JSON. This seems like a major oversight though.. I simply don’t accept that there is no way to get around this warning…