Main Tutorials

JSON.simple – 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)

Warning
This article is using the old JSON.simple 1.x ,which is deprecated and no longer maintained by the author. Please visit this upgraded article – JSON.simple 3.x – How to parse JSON
Why not Jackson or Gson?
You may have interest to read this article – How to parse JSON with Jackson or Gson

1. Download JSON.simple

pom.xml

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

2. Write JSON to File

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", 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("c:\\projects\\test.json")) {
            file.write(obj.toJSONString());
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.print(obj);

    }

}

Output

Terminal

{"name":"mkyong.com","messages":["msg 1","msg 2","msg 3"],"age":100}
c:\\projects\\test.json

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

3. Read JSON to File

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.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.Iterator;

public class JsonSimpleReadExample {

    public static void main(String[] args) {

        JSONParser parser = new JSONParser();

        try (Reader reader = new FileReader("c:\\projects\\test.json")) {

            JSONObject jsonObject = (JSONObject) parser.parse(reader);
            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 (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }

    }


}

Output

Terminal

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

References

About Author

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

Comments

Subscribe
Notify of
101 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Subhrajit Bhattacharya
7 years ago

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

Alexandre luz
8 years ago

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)

Aftab
4 years ago
Reply to  Alexandre luz

I thing you just copied the code.
and have not files that imported the top.
so you must have file like,
import org.json.simple.JSONArray;
this is a file located somewhere.

Maks
10 years ago

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

Samuel
2 years ago
Reply to  Maks

if you start the try catch with (Reader…) it closes itself

Vijay
10 years ago

Big Help 🙂

Artem Melnik
1 year ago

Thank you!

Ren
4 years ago

Mkyong, thanks a lot for your articles!
So many times you give me a hand by your articles!
Just want to say Great Thank to you! You are the best! 🙂

Jajang Nurhadi
5 years ago

thank you bro. u my task saver

Mihir Monani
8 years ago

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??

Morgan
10 years ago

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.

kanangkuan
10 years ago

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” : ” ”

}

]

}

]

}

anil kumar
7 years ago
Reply to  kanangkuan

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) {

}

Tian Zheng
9 years ago
Reply to  kanangkuan

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

ajay
9 years ago
Reply to  Tian Zheng

“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

Vincent
2 years ago

Thank you for your article, simple and clear. But how do I create a JSON with multiple objects?

Salman Rahman
2 years ago

you missed to add this line after converting your object to json file:
file.flush();

ibaskorn
3 years ago

how write string “/test”
error result on json “\/test”

Peter Schorn
3 years ago

You don’t read to a file; you read from a file.

Bharat
3 years ago

here it’s showing NULL for my execution,
Reading Json file
city: null
state: null
country: null
can you help me on this?

Jon
4 years ago

Can you put some info here on why using javax.json may or may not be ideal in certain situations? You mention Gson and Jackson, so I thought it might be useful to mention the javax lib?

Kuntal Paul
5 years ago

I am trying to read a json file using the code mentioned above, however I keep on getting following error at the line ‘ JSONObject jsonObject = (JSONObject) obj;’, please help.

Exception in thread “main” java.lang.ClassCastException: org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject
at StockJsonRead.main(StockJsonRead.java:21)

alex
5 years ago

I am trying to write from mysql a json file. I do not know what is wrong with my code. When I write
http://localhost:8085/Json3/testjson.jsp the information apprears on the screen as follows:

[{“Nombre”:”Nancy”,”Cargo”:”Sales Representative”,”Empresa”:”Northwind Traders”},{“Nombre”:”Andrew”,”Cargo”:”Vice President, Sales”,”Empresa”:”Northwind Traders”},{“Nombre”:”Jan”,”Cargo”:”Sales Representative”,”Empresa”:”Northwind Traders”},{“Nombre”:”Mariya”,”Cargo”:”Sales Representative”,”Empresa”:”Northwind Traders”},{“Nombre”:”Steven”,”Cargo”:”Sales Manager”,”Empresa”:”Northwind Traders”},{“Nombre”:”Michael”,”Cargo”:”Sales Representative”,”Empresa”:”Northwind Traders”},{“Nombre”:”Robert”,”Cargo”:”Sales Representative”,”Empresa”:”Northwind Traders”},{“Nombre”:”Laura”,”Cargo”:”Sales Coordinator”,”Empresa”:”Northwind Traders”},{“Nombre”:”Anne”,”Cargo”:”Sales Representative”,”Empresa”:”Northwind Traders”},{“Nombre”:”Alex”,”Cargo”:”ing.”,”Empresa”:”acme”}]

But I need to write this information json in a .json file. Before I created a blank file “nuevo.json” and is located as follows: (Netbeans)

Json3 (project)
webpages
index.html
nuevo.json
testjson.jsp

testjson.jsp contains the following:

When I see the “nuevo.json” is empty……….I tried changing FileWriter file = new FileWriter(“nuevo.json”);
for
FileWriter file = new FileWriter(“http://localhost:8085/Json3/nuevo.json”);
but the nuevo.json file was empty.

fds
5 years ago

what about pârsing unknown dictionnary ?

Sourabh
5 years ago

How to read json file from classpath (resource folder)

swati singh
7 years ago

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
6 years ago
Reply to  swati singh

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

Madhu Sudhan Baddam
8 years ago

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”

}

nikhil
8 years ago

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

amal
9 years ago

very helpful really great and simple example

Majid Lotfi
9 years ago

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.

prasanth
9 years ago

how can i get json array in highchart

Robson Carvalho
9 years ago

Thank you!

Nathan Watts
9 years ago

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
9 years ago

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

Michael Wiggins
8 years ago
Reply to  Ali Gajani

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
10 years ago

Great example thankyou.