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
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
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
mkyong. Just wanted to say thanks for your articles. They are simple and clear, and they have benefited me very much.
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)
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.
It is hard to guess, unless shown your source code here. Just tested and the code is working fine.
Try this new JSON.simple examples
https://www.mkyong.com/java/json-simple-how-to-parse-json/
Hello,
I have a question. Shouldn’t be the FileReader closed too? The same way as a FileWriter instance in example above?
if you start the try catch with (Reader…) it closes itself
Big Help 🙂
Thank you!
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! 🙂
thank you bro. u my task saver
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??
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.
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” : ” ”
}
]
}
]
}
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) {
}
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
Thank you for your article, simple and clear. But how do I create a JSON with multiple objects?
you missed to add this line after converting your object to json file:
file.flush();
how write string “/test”
error result on json “\/test”
You don’t read to a file; you read from a file.
here it’s showing NULL for my execution,
Reading Json file
city: null
state: null
country: null
can you help me on this?
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?
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)
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.
what about pârsing unknown dictionnary ?
How to read json file from classpath (resource folder)
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”
}
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
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.
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.