How to read and write JSON with json-simple
json
json-simple
java
JSONObject
JSONArray
Json-simple is a simple java library used to encode and decode JSON. It is full compliance with JSON specification (RFC4627) and is widely used in big projects, see the website for details.
Step1 - Dependency
If you are using a maven structure for your project you can added as dependency:
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
otherwise download the jar file and attached it to the project.
Step2 - Generate the JSON object
To generate an object use JSONObject
and add the content similar to Map/Hashmap.
/* Create simple object */
JSONObject object = new JSONObject();
object.put("id", new Integer(1001));
object.put("name", "John Doe");
or if you need an array you can use JSONArray
:
/* json array added manually */
JSONArray array = new JSONArray();
array.add("product 1");
array.add("product 2");
/* json array added from an ArrayList object */
ArrayList<String> list = new ArrayList<String>();
list.add("list element 1");
list.add("list element 2");
list.add("list element 3");
array.addAll(list);
Also can be created complex JSON structures by adding an JSONObject
on other JSONObject
.
/* add the list to initial object */
object.put("list", array);
Step3 - Write the JSON object to file
To write the json to a file will use FileWriter from java.io
package.
/* write the complex object to a file */
try {
FileWriter file = new FileWriter("test.json");
file.write(object.toString());
file.flush();
file.close();
} catch (IOException e) {
e.printStackTrace();
}
Note: the path for the file is the folder root of the project.
Step4 - Read the JSON from file
To recreate the JSONObject json-simple library provides a class to parse the input, JSONParser and this can use multiple sources.
JSONParser parser = new JSONParser();
/* Get the file content into the JSONObject */
Object obj = parser.parse(new FileReader("test.json"));
JSONObject jsonObject = (JSONObject)obj;
From this point you have access to all object within jsonObject.
Example
Here is the print for the entire example:
package com.admfactory.json;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class JsonSimpleTests {
/**
* How to create an JSON object and write it to a file
*/
public static void createJSONObject() {
System.out.println("Write an JSON Object");
/* Create simple object */
JSONObject object = new JSONObject();
object.put("id", new Integer(1001));
object.put("name", "John Doe");
System.out.println("Simple object: " + object);
/* json array added manualy */
JSONArray array = new JSONArray();
array.add("product 1");
array.add("product 2");
/* json array added from an ArrayList object */
ArrayList<String> list = new ArrayList<String>();
list.add("list element 1");
list.add("list element 2");
list.add("list element 3");
array.addAll(list);
System.out.println("Array object: " + array);
/* add the list to initial object */
object.put("list", array);
System.out.println("Complex object:" + object);
/* write the complex object to a file */
try {
FileWriter file = new FileWriter("test.json");
file.write(object.toString());
file.flush();
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* How to read an json object from a file and display it on the console
*
*/
public static void readJSONObject() {
JSONParser parser = new JSONParser();
try {
/* Get the file content into the JSONObject */
Object obj = parser.parse(new FileReader("test.json"));
JSONObject jsonObject = (JSONObject)obj;
System.out.println("Object from file:" + jsonObject);
/* Read simple value */
Long id = (Long)jsonObject.get("id");
System.out.println("id:"+id);
/* Read a list */
ArrayList<String> list = (ArrayList<String>)jsonObject.get("list");
for (int i = 0; i < list.size(); i++) {
System.out.println(i+ ": " + list.get(i));
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
System.out.println("json-simple examples");
System.out.println();
createJSONObject();
System.out.println();
readJSONObject();
}
}
Output
The console output from our test program. Check also the content of the test.json file located in root folder of your project.
json-simple examples
Write an JSON Object
Simple object: {"id":1001,"name":"John Doe"}
Array object: ["product 1","product 2","list element 1","list element 2","list element 3"]
Complex object:{"id":1001,"name":"John Doe","list":["product 1","product 2","list element 1","list element 2","list element 3"]}
Object from file:{"id":1001,"name":"John Doe","list":["product 1","product 2","list element 1","list element 2","list element 3"]}
id:1001
0: product 1
1: product 2
2: list element 1
3: list element 2
4: list element 3
References
- Json-simple website.
- Maven Search Json-simple page.