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 the Author

author image
mkyong
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

avatar
78 Comment threads
21 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
84 Comment authors
AftabmkyongJonJajang NurhadiKuntal Paul Recent comment authors
newest oldest most voted
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)

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.

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.

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?

Vijay
Guest
Vijay

Big Help 🙂

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

}

]

}

]

}

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

devGuru
Guest
devGuru

Thank you! This is the simplest and most helpful tutorial/example I have found on JSON and Java.

zimmi
Guest
zimmi

What if I have JSON with more than one item? When I try to go through such file JSONSimple gives unexpected character error on left brace of the next object. Is it able to handle just one entry per file? This seems rather strange to me, I must be doing something wrong.

Shawn
Guest
Shawn

Just wanted to thank you for providing a SIMPLE example of reading and writing JSON in java… for some reason every example out there wanted to over complicate the task for no reason.

trackback
JSON reader

[…] it was as the documentation is overly complicated for the task… here's the link I followed: LINK. I hope this helps make it easier on anyone else that ran into the problem. […]

trackback
JSON introduction and Java/Android tutorial « Looks OK!

[…] & Parsing JSON data with Java JSON in Android – Tutorial JSON.simple example – Read and write JSON Share this:Like this:LikeBe the first to like […]

Pavan
Guest
Pavan

Thanks, this example is simple and easy understandable.

cc
Guest
cc

good

gio
Guest
gio

Hi, I’ve copied the code but it doesn’t work… the error is:Lexical Error: Unmatched Input.
Why??? what I should change?
I use the json file of the above example.
Thanks

fakhar
Guest
fakhar

The following link is also useful if you want to use com.google.gson library to read JSON files : http://usmanali112.blogspot.com/2012/07/java-read-json-files.html

liu
Guest
liu

hi, thanks for it, BUT i have question for it. if i only want to insert some data in this json file, NOT cover it, how i sould do?? thank you !

Mal
Guest
Mal

I’m trying to read simple json file into my java code but it gives me ClassCastException

JSONParser parser = new JSONParser();
JSONObject jobj = (JSONObject) parser.parse(new FileReader(“src/test/resources/test.json”));

any idea what could be wrong with that?

Amoy
Guest
Amoy

Thank you!
This is the simplest and most helpful tutorial/example I have found on JSON and Java (quoted form devGuru) too !!

trackback
Why does my JSON-Simple JSONArray give me a nullpointer exception? | Jisku.com - Developers Network

[…] does my JSON-Simple JSONArray give me a nullpointer exception? I’m following this tutuorial here, and my JSON object is near enough the same, except I have this sort of […]

Rashi..
Guest
Rashi..

Very nice one.. Thanks a lot.. 🙂

Paritosh
Guest
Paritosh

Thank you it was pretty easy to understand.

Aparna
Guest
Aparna

Very Simple and Nice example, but does not work for me. JsonParser is an abstract class and cannot be instantiated.

Aparna
Guest
Aparna

Simple example but unable to use. JsonParser is an abstract class

Parveen Verma
Guest
Parveen Verma

Thank you so much……really very much beneficial it is 🙂

Ajay Kumar
Guest
Ajay Kumar

Simplest and very helpful tutorial. Thanks alot for keep me in safe jone.

Yorker Ball
Guest
Yorker Ball

Please visit http://www.luvcelebs.com to check more…

Vinod
Guest
Vinod

Thank you very much!. Helped me.

trackback
So, Let’s Organise Our Web Scrape? HEY JSON. | scitasy

[…] of all, I used the JSON.simple library to do all of this. Go HERE to download the jar. I also used mkywong’s tutorial to figure out what goes […]

trackback
Microsoft Exam 70-480 Certification Tips | Xtiology

[…] http://www.mkyong.com/java/json-simple-example-read-and-write-json/ (The example given is from java though the logic and the JSON code is just the same.) […]