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
To convert object to / from JSON, you should consider Jackson 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, just declares following dependency in your pom.xml file.

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

2. Write JSON to file

In below example, it write JSON data via JSONObject and JSONArray, and save it into a file named “test.json“.

import java.io.FileWriter;
import java.io.IOException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
 
public class JsonSimpleExample {
     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("c:\\test.json");
		file.write(obj.toJSONString());
		file.flush();
		file.close();
 
	} catch (IOException e) {
		e.printStackTrace();
	}
 
	System.out.print(obj);
 
     }
 
}

Output – See content of file named “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 “test.json“, and display each of the values.

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
 
public class JsonSimpleExample {
     public static void main(String[] args) {
 
	JSONParser parser = new JSONParser();
 
	try {
 
		Object obj = parser.parse(new FileReader("c:\\test.json"));
 
		JSONObject jsonObject = (JSONObject) obj;
 
		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

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

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.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

  • Pingback: water ionizer()

  • Pingback: watch movies online free()

  • Pingback: free movie downloads()

  • Pingback: watch tv show episodes()

  • Pingback: Blue Coaster33()

  • http://- aga

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

  • Kishore

    error at
    msg.iterator();

  • bidhu

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

    • Shero

      Try reading? Dumbass.

  • a

    ddd

  • 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

      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

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

  • Manuaran

    here is the answer.

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

    • codegirl

      are you trying to answer me?

  • 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 cannot be parameterized with arguments <String, "

    I am hoping you can provide a solutions that is better than just "@surpress warning"?

    Has anyone else encountered this issue?

    • 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…

  • http://blog.naver.com/cestlavie_01 cobus

    Thanks a lot. You make me smile.

  • bidhu prasad panda

    hi i am getting
    Exception in thread “main” java.lang.NullPointerException
    at java.io.Writer.write(Writer.java:127)
    at JsonSimpleExample.main(JsonSimpleExample.java:23)
    these errors after compiling JsonSimpleExample.java file.
    Please help me to solve this one…I need it.Please.

    regards

  • mamta

    Hi, It was a useful aricle. But just wanna check with you guys has any one tries fetching the json array elements using Selenium IDE? I was ale to extract the json object but was not able to extract the array from json object… any one any idea .. ? even small help is appreciated.

  • Trimi-albania

    A very simple Example, helps lot!

    Thanky you :D

    Which version of simple-json did you use?

  • Vijay

    Big Help :)

  • Pingback: Java – Convert String to String Array : Android Community - For Application Development()

  • Pingback: Microsoft Exam 70-480 Certification Tips | Xtiology()

  • Pingback: So, Let’s Organise Our Web Scrape? HEY JSON. | scitasy()

  • Vinod

    Thank you very much!. Helped me.

  • http://www.luvcelebs.com Yorker Ball

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

  • Ajay Kumar

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

  • Parveen Verma

    Thank you so much……really very much beneficial it is :)

  • Aparna

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

  • Aparna

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

    • Ram

      Please add the jar file to ur project….Will work den..

  • Paritosh

    Thank you it was pretty easy to understand.

  • http://www.facebook.com/Rashi325 Rashi..

    Very nice one.. Thanks a lot.. :)

  • Pingback: Why does my JSON-Simple JSONArray give me a nullpointer exception? | Jisku.com - Developers Network()

  • Amoy

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

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

  • 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 !

  • 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

  • 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

  • cc

    good

  • Pavan

    Thanks, this example is simple and easy understandable.

  • Pingback: JSON introduction and Java/Android tutorial « Looks OK!()

  • Pingback: JSON reader()

  • http://none 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.

  • http://zimmicz.posterous.com 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.

    • EugSeverinho

      I have the same problem, maybe catch newlines would help

  • devGuru

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

    • mahesh

      This tutorial is very much useful for all the developers