Org.json library
Basic usage to generate JSON Data
org.json uses its JSONObject (Java Doc) class to create or parse JSON. JSONObject APIs work much like the Java Map APIs and are simple to use.When you need to print out, you should transform it to String, .toString().1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27import org.json.JSONObject;
private static void createJSON(boolean prettyPrint) {
JSONObject tomJsonObj = new JSONObject();
tomJsonObj.put("name", "Tom");
tomJsonObj.put("birthday", "1940-02-10");
tomJsonObj.put("age", 76);
tomJsonObj.put("married", false);
// Cannot set null directly
tomJsonObj.put("car", JSONObject.NULL);
tomJsonObj.put("favorite_foods", new String[] { "cookie", "fish", "chips" });
// {"id": 100001, "nationality", "American"}
JSONObject passportJsonObj = new JSONObject();
passportJsonObj.put("id", 100001);
passportJsonObj.put("nationality", "American");
// Value of a key is a JSONObject
tomJsonObj.put("passport", passportJsonObj);
if (prettyPrint) {
// With four indent spaces
System.out.println(tomJsonObj.toString(4));
} else {
System.out.println(tomJsonObj.toString());
}
}
Convert Json object into Java Map object
JSONObject provided a constructor to convert key-value pairs data to JSON object from Java Map object.
<% start codeblock %>
` // Create JSON object from Java Map
JSONObject tomJsonObj = new JSONObject(tom);``
<% endcodeblock %>
Create JSON Object from Java Bean
Should use Bean instance to initialize this JSON object;JSONObject tomJsonObj = new JSONObject(tom);
Parse JSON String into JSON object
<% start codeblock %>
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.json.JSONObject;
private static void readJSON() throws Exception {
File file = new File(“./tom.json”);
String content = FileUtils.readFileToString(file, “utf-8”);
// Convert JSON string to JSONObject
JSONObject tomJsonObject = new JSONObject(content);
// Access the attribute of this JSON data
String name = tomJsonObject.getString("name");
Integer age = tomJsonObject.getInt("Age");
}
<% endcodeblock %>