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).
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
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)
mkyong. Just wanted to say thanks for your articles. They are simple and clear, and they have benefited me very much.
Hello,
I have a question. Shouldn’t be the FileReader closed too? The same way as a FileWriter instance in example above?
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
make sure you’ve imported org.json.simple.JSONArray and not org.json.JSONArray
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”
}
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??
consider i have Json file and i need to append more json data to it . how can i do it]
very helpful really great and simple example
I guess you are a Chinese, shake hand. ;)
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.
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.
how can i get json array in highchart
Thank you!
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();
….
….
….
….
This doesn’t work when you have greater than 1 JSON ? How to do it recursively?
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.
Great example thankyou.
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.
For the following line in the reading example the word long should probably be capitalized:
long age = (Long) jsonObject.get(“age”);
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
Nice explanation :)
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” : ” ”
}
]
}
]
}
I believe the best solution is to create a JSONArray that is called “children” with several “child” JSONObjects in it.
“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
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) { }
this same process of reading and writing from/to JSON applies to Blackberry application OS 7 as well?
Thank you in advance
error at
msg.iterator();
What is the need of that .xml code.
Can any one plz explain me.
Try reading? Dumbass.
Name calling is quite unnecessary on a programming forum, isn’t it. You sound like a schoolyard bully.
ddd
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.
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());
}
}
here is the answer.
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader(“/Users//Documents/file1.txt”));
are you trying to answer me?
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 »
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…
Thanks a lot. You make me smile.
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
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.
hi
u got output.If yes please help me.
I am getting errors like
Exception in thread “main” java.lang.NullPointerException
at java.io.Writer.write(Writer.java:127)
at JsonSimpleExample.main(JsonSimpleExample.java:23)
and another thing where to put that .xml file.
http://stackoverflow.com/questions/10746671/selenium-test-parse-json-string-from-variable
Refer to this link .. it solved my problem