Json Simple 简明教程
JSON.simple - Overview
JSON.simple 是一个基于 Java 的简单工具包,适用于 JSON。你可以使用 JSON.simple 对 JSON 数据进行编码或解码。
JSON.simple is a simple Java based toolkit for JSON. You can use JSON.simple to encode or decode JSON data.
Features
-
Specification Compliant − JSON.simple is fully compliant with JSON Specification - RFC4627.
-
Lightweight − It have very few classes and provides the necessary functionalities like encode/decode and escaping json.
-
Reuses Collections − Most of the operations are done using Map/List interfaces increasing the reusablity.
-
Streaming supported − Supports streaming of JSON output text.
-
SAX like Content Handler − Provides a SAX-like interface to stream large amount of JSON data.
-
High performance − Heap based parser is used and provide high performance.
-
No dependency − No external library dependency. Can be independently included.
-
JDK1.2 compatible − Source code and the binary are JDK1.2 compatible
JSON.simple - Environment Setup
Local Environment Setup
JSON.simple 是一个用于 Java 的库,因此首要要求是在你的机器上安装 JDK。
JSON.simple is a library for Java, so the very first requirement is to have JDK installed in your machine.
Step 1: Verify Java Installation in Your Machine
首先,打开控制台并根据您正在使用的操作系统执行 java 命令。
First of all, open the console and execute a java command based on the operating system you are working on.
OS |
Task |
Command |
Windows |
Open Command Console |
c:> java -version |
Linux |
Open Command Terminal |
$ java -version |
Mac |
Open Terminal |
machine:< joseph$ java -version |
让我们验证所有操作系统的输出 −
Let’s verify the output for all the operating systems −
OS |
Output |
Windows |
java version "1.8.0_101" Java™ SE Runtime Environment (build 1.8.0_101) |
Linux |
java version "1.8.0_101" Java™ SE Runtime Environment (build 1.8.0_101) |
Mac |
java version "1.8.0_101" Java™ SE Runtime Environment (build 1.8.0_101) |
如果你尚未在自己的系统上安装 Java,请从 www.oracle.com 以下链接下载 Java 软件开发工具包 (SDK)。对于本教程,我们假设安装的版本是 Java 1.8.0_101。
If you do not have Java installed on your system, then download the Java Software Development Kit (SDK) from the following link www.oracle.com. We are assuming Java 1.8.0_101 as the installed version for this tutorial.
Step 2: Set JAVA Environment
将 JAVA_HOME 环境变量设置为您计算机中安装 Java 的基本目录位置。例如。
Set the JAVA_HOME environment variable to point to the base directory location where Java is installed on your machine. For example.
OS |
Output |
Windows |
Set the environment variable JAVA_HOME to C:\Program Files\Java\jdk1.8.0_101 |
Linux |
export JAVA_HOME = /usr/local/java-current |
Mac |
export JAVA_HOME = /Library/Java/Home |
在系统路径中追加 Java 编译器位置。
Append Java compiler location to the System Path.
OS |
Output |
Windows |
Append the string C:\Program Files\Java\jdk1.8.0_101\bin at the end of the system variable, Path. |
Linux |
export PATH = $PATH:$JAVA_HOME/bin/ |
Mac |
not required |
如上所述,使用命令 java -version 验证 Java 安装。
Verify Java installation using the command java -version as explained above.
Step 3: Download JSON.simple Archive
从 json-simple @ MVNRepository 下载 JSON.simple jar 文件的最新版本。在本教程编写时,我们已经下载了 json-simple-1.1.1.jar,并将其复制到了 C:\>JSON 文件夹。
Download the latest version of JSON.simple jar file from json-simple @ MVNRepository. At the time of writing this tutorial, we have downloaded json-simple-1.1.1.jar, and copied it into C:\>JSON folder.
OS |
Archive name |
Windows |
json-simple-1.1.1.jar |
Linux |
json-simple-1.1.1.jar |
Mac |
json-simple-1.1.1.jar |
Step 4: Set JSON_JAVA Environment
将 JSON_JAVA 环境变量设置为你机器上存储 JSON.simple jar 的基本目录位置。让我们假设我们已经将 json-simple-1.1.1.jar 存储在 JSON 文件夹中。
Set the JSON_JAVA environment variable to point to the base directory location where JSON.simple jar is stored on your machine. Let’s assuming we’ve stored json-simple-1.1.1.jar in the JSON folder.
Sr.No |
OS & Description |
1 |
Windows Set the environment variable JSON_JAVA to C:\JSON |
2 |
Linux export JSON_JAVA = /usr/local/JSON |
3 |
Mac export JSON_JAVA = /Library/JSON |
Step 5: Set CLASSPATH Variable
将 CLASSPATH 环境变量设置为指向 JSON.simple jar 所在位置。
Set the CLASSPATH environment variable to point to the JSON.simple jar location.
Sr.No |
OS & Description |
1 |
Windows Set the environment variable CLASSPATH to %CLASSPATH%;%JSON_JAVA%\json-simple-1.1.1.jar;.; |
2 |
Linux export CLASSPATH = $CLASSPATH:$JSON_JAVA/json-simple-1.1.1.jar:. |
3 |
Mac export CLASSPATH = $CLASSPATH:$JSON_JAVA/json-simple-1.1.1.jar:. |
JSON.simple - JAVA Mapping
JSON.simple 在解码或解析时将实体从左侧映射到右侧,在编码时将实体从右侧映射到左侧。
JSON.simple maps entities from the left side to the right side while decoding or parsing, and maps entities from the right to the left while encoding.
JSON |
Java |
string |
java.lang.String |
number |
java.lang.Number |
true |
false |
java.lang.Boolean |
null |
null |
array |
java.util.List |
object |
在解码时,java.util.List 的默认具体类是 org.json.simple.JSONArray,而 java.util.Map 的默认具体类是 org.json.simple.JSONObject。
On decoding, the default concrete class of java.util.List is org.json.simple.JSONArray and the default concrete class of java.util.Map is org.json.simple.JSONObject.
JSON.simple - Escaping Special Characters
以下字符是保留字符,不能在 JSON 中使用,必须进行适当转义才能在字符串中使用。
The following characters are reserved characters and can not be used in JSON and must be properly escaped to be used in strings.
-
Backspace to be replaced with \b
-
Form feed to be replaced with \f
-
Newline to be replaced with \n
-
Carriage return to be replaced with \r
-
Tab to be replaced with \t
-
Double quote to be replaced with \"
-
Backslash to be replaced with \\
JSONObject.escape() 方法可用于转义 JSON 字符串中的此类保留关键字。以下是示例 −
JSONObject.escape() method can be used to escape such reserved keywords in a JSON String. Following is the example −
Example
import org.json.simple.JSONObject;
public class JsonDemo {
public static void main(String[] args) {
JSONObject jsonObject = new JSONObject();
String text = "Text with special character /\"\'\b\f\t\r\n.";
System.out.println(text);
System.out.println("After escaping.");
text = jsonObject.escape(text);
System.out.println(text);
}
}
JSON.simple - Using JSONValue
JSONValue 提供静态方法 parse(),用于解析给定的 json 字符串以返回 JSONObject,然后可以使用它来获取已解析的值。请参阅下面的示例。
JSONValue provide a static method parse() to parse the given json string to return a JSONObject which can then be used to get the values parsed. See the example below.
Example
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
public class JsonDemo {
public static void main(String[] args) {
String s = "[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]";
Object obj = JSONValue.parse(s);
JSONArray array = (JSONArray)obj;
System.out.println("The 2nd element of array");
System.out.println(array.get(1));
System.out.println();
JSONObject obj2 = (JSONObject)array.get(1);
System.out.println("Field \"1\"");
System.out.println(obj2.get("1"));
s = "{}";
obj = JSONValue.parse(s);
System.out.println(obj);
s = "[5,]";
obj = JSONValue.parse(s);
System.out.println(obj);
s = "[5,,2]";
obj = JSONValue.parse(s);
System.out.println(obj);
}
}
JSON.simple - Exception Handling
JSONParser.parse() 在 JSON 无效的情况下会引发 ParseException。以下示例演示了如何处理 ParseException。
JSONParser.parse() throws ParseException in case of invalid JSON. Following example shows how to handle ParseException.
Example
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
class JsonDemo {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
String text = "[[null, 123.45, \"a\tb c\"]}, true";
try{
Object obj = parser.parse(text);
System.out.println(obj);
}catch(ParseException pe) {
System.out.println("position: " + pe.getPosition());
System.out.println(pe);
}
}
}
JSON.simple - Container Factory
ContainerFactory 可用于为已解析的 JSON 对象/数组创建自定义容器。首先,我们需要创建一个 ContainerFactory 对象,然后在 JSONParser 的 parse 方法中使用它以获取所需的 objects。请参阅下面的示例 −
ContainerFactory can be used to create Custom container for parsed JSON objects/arrays. First we need to create a ContainerFactory object and then use it in parse Method of JSONParser to get the required object. See the example below −
Example
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.json.simple.parser.ContainerFactory;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
class JsonDemo {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
String text = "{\"first\": 123, \"second\": [4, 5, 6], \"third\": 789}";
ContainerFactory containerFactory = new ContainerFactory() {
@Override
public Map createObjectContainer() {
return new LinkedHashMap<>();
}
@Override
public List creatArrayContainer() {
return new LinkedList<>();
}
};
try {
Map map = (Map)parser.parse(text, containerFactory);
map.forEach((k,v)->System.out.println("Key : " + k + " Value : " + v));
} catch(ParseException pe) {
System.out.println("position: " + pe.getPosition());
System.out.println(pe);
}
}
}
JSON.simple - ContentHandler
ContentHandler 接口用于提供类似 SAX 的接口来流式处理大型 json。它还提供了可停止的功能。以下示例说明了此概念。
ContentHandler interface is used to provide a SAX like interface to stream the large json. It provides stoppable capability as well. Following example illustrates the concept.
Example
import java.io.IOException;
import java.util.List;
import java.util.Stack;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.ContentHandler;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
class JsonDemo {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
String text = "{\"first\": 123, \"second\": [4, 5, 6], \"third\": 789}";
try {
CustomContentHandler handler = new CustomContentHandler();
parser.parse(text, handler,true);
} catch(ParseException pe) {
}
}
}
class CustomContentHandler implements ContentHandler {
@Override
public boolean endArray() throws ParseException, IOException {
System.out.println("inside endArray");
return true;
}
@Override
public void endJSON() throws ParseException, IOException {
System.out.println("inside endJSON");
}
@Override
public boolean endObject() throws ParseException, IOException {
System.out.println("inside endObject");
return true;
}
@Override
public boolean endObjectEntry() throws ParseException, IOException {
System.out.println("inside endObjectEntry");
return true;
}
public boolean primitive(Object value) throws ParseException, IOException {
System.out.println("inside primitive: " + value);
return true;
}
@Override
public boolean startArray() throws ParseException, IOException {
System.out.println("inside startArray");
return true;
}
@Override
public void startJSON() throws ParseException, IOException {
System.out.println("inside startJSON");
}
@Override
public boolean startObject() throws ParseException, IOException {
System.out.println("inside startObject");
return true;
}
@Override
public boolean startObjectEntry(String key) throws ParseException, IOException {
System.out.println("inside startObjectEntry: " + key);
return true;
}
}
Output
inside startJSON
inside startObject
inside startObjectEntry: first
inside primitive: 123
inside endObjectEntry
inside startObjectEntry: second
inside startArray
inside primitive: 4
inside primitive: 5
inside primitive: 6
inside endArray
inside endObjectEntry
inside startObjectEntry: third
inside primitive: 789
inside endObjectEntry
inside endObject
inside endJSON
JSON.simple - Encode JSONObject
使用 JSON.simple,我们可以使用以下方法对 JSON 对象进行编码 −
Using JSON.simple, we can encode a JSON Object using following ways −
-
Encode a JSON Object - to String − Simple encoding.
-
Encode a JSON Object - Streaming − Output can be used for streaming.
-
Encode a JSON Object - Using Map − Encoding by preserving the order.
-
Encode a JSON Object - Using Map and Streaming − Encoding by preserving the order and to stream.
以下示例说明了上述概念。
Following example illustrates the above concepts.
Example
import java.io.IOException;
import java.io.StringWriter;
import java.util.LinkedHashMap;
import java.util.Map;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
class JsonDemo {
public static void main(String[] args) throws IOException {
JSONObject obj = new JSONObject();
String jsonText;
obj.put("name", "foo");
obj.put("num", new Integer(100));
obj.put("balance", new Double(1000.21));
obj.put("is_vip", new Boolean(true));
jsonText = obj.toString();
System.out.println("Encode a JSON Object - to String");
System.out.print(jsonText);
StringWriter out = new StringWriter();
obj.writeJSONString(out);
jsonText = out.toString();
System.out.println("\nEncode a JSON Object - Streaming");
System.out.print(jsonText);
Map obj1 = new LinkedHashMap();
obj1.put("name", "foo");
obj1.put("num", new Integer(100));
obj1.put("balance", new Double(1000.21));
obj1.put("is_vip", new Boolean(true));
jsonText = JSONValue.toJSONString(obj1);
System.out.println("\nEncode a JSON Object - Preserving Order");
System.out.print(jsonText);
out = new StringWriter();
JSONValue.writeJSONString(obj1, out);
jsonText = out.toString();
System.out.println("\nEncode a JSON Object - Preserving Order and Stream");
System.out.print(jsonText);
}
}
Output
Encode a JSON Object - to String
{"balance":1000.21,"is_vip":true,"num":100,"name":"foo"}
Encode a JSON Object - Streaming
{"balance":1000.21,"is_vip":true,"num":100,"name":"foo"}
Encode a JSON Object - Preserving Order
{"name":"foo","num":100,"balance":1000.21,"is_vip":true}
Encode a JSON Object - Preserving Order and Stream
{"name":"foo","num":100,"balance":1000.21,"is_vip":true}
JSON.simple - Encode JSONArray
使用 JSON.simple,我们可以使用以下方法对 JSON 数组进行编码 −
Using JSON.simple, we can encode a JSON Array using following ways −
-
Encode a JSON Array - to String − Simple encoding.
-
Encode a JSON Array - Streaming − Output can be used for streaming.
-
Encode a JSON Array - Using List − Encoding by using the List.
-
Encode a JSON Array - Using List and Streaming − Encoding by using List and to stream.
以下示例说明了上述概念。
Following example illustrates the above concepts.
Example
import java.io.IOException;
import java.io.StringWriter;
import java.util.LinkedList;
import java.util.List;
import org.json.simple.JSONArray;
import org.json.simple.JSONValue;
class JsonDemo {
public static void main(String[] args) throws IOException {
JSONArray list = new JSONArray();
String jsonText;
list.add("foo");
list.add(new Integer(100));
list.add(new Double(1000.21));
list.add(new Boolean(true));
list.add(null);
jsonText = list.toString();
System.out.println("Encode a JSON Array - to String");
System.out.print(jsonText);
StringWriter out = new StringWriter();
list.writeJSONString(out);
jsonText = out.toString();
System.out.println("\nEncode a JSON Array - Streaming");
System.out.print(jsonText);
List list1 = new LinkedList();
list1.add("foo");
list1.add(new Integer(100));
list1.add(new Double(1000.21));
list1.add(new Boolean(true));
list1.add(null);
jsonText = JSONValue.toJSONString(list1);
System.out.println("\nEncode a JSON Array - Using List");
System.out.print(jsonText);
out = new StringWriter();
JSONValue.writeJSONString(list1, out);
jsonText = out.toString();
System.out.println("\nEncode a JSON Array - Using List and Stream");
System.out.print(jsonText);
}
}
JSON.simple - Merging Objects
在 JSON.simple 中,我们可以轻松使用 JSONObject.putAll() 方法合并两个 JSON 对象。
In JSON.simple, we can merge two JSON Objects easily using JSONObject.putAll() method.
以下示例说明了上述概念。
Following example illustrates the above concept.
Example
import java.io.IOException;
import org.json.simple.JSONObject;
class JsonDemo {
public static void main(String[] args) throws IOException {
JSONObject obj1 = new JSONObject();
obj1.put("name", "foo");
obj1.put("num", new Integer(100));
JSONObject obj2 = new JSONObject();
obj2.put("balance", new Double(1000.21));
obj2.put("is_vip", new Boolean(true));
obj1.putAll(obj2);
System.out.println(obj1);
}
}
JSON.simple - Merging Arrays
在 JSON.simple 中,我们可以轻松使用 JSONArray.addAll() 方法合并两个 JSON 数组。
In JSON.simple, we can merge two JSON Arrays easily using JSONArray.addAll() method.
以下示例说明了上述概念。
Following example illustrates the above concept.
Example
import java.io.IOException;
import org.json.simple.JSONArray;
class JsonDemo {
public static void main(String[] args) throws IOException {
JSONArray list1 = new JSONArray();
list1.add("foo");
list1.add(new Integer(100));
JSONArray list2 = new JSONArray();
list2.add(new Double(1000.21));
list2.add(new Boolean(true));
list2.add(null);
list1.addAll(list2);
System.out.println(list1);
}
}
JSON.simple - Primitive, Object, Array
使用 JSONArray 对象,我们可以创建一个包含基本类型、对象和数组的 JSON。
Using JSONArray object, we can create a JSON which comprises of primitives, object and array.
以下示例说明了上述概念。
Following example illustrates the above concept.
Example
import java.io.IOException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
class JsonDemo {
public static void main(String[] args) throws IOException {
JSONArray list1 = new JSONArray();
list1.add("foo");
list1.add(new Integer(100));
JSONArray list2 = new JSONArray();
list2.add(new Double(1000.21));
list2.add(new Boolean(true));
list2.add(null);
JSONObject obj = new JSONObject();
obj.put("name", "foo");
obj.put("num", new Integer(100));
obj.put("balance", new Double(1000.21));
obj.put("is_vip", new Boolean(true));
obj.put("list1", list1);
obj.put("list2", list2);
System.out.println(obj);
}
}
JSON.simple - Primitive, Map, List Combination
使用 JSONValue 对象,我们可以创建一个包含基本类型、映射和列表的 JSON。
Using JSONValue object, we can create a JSON which comprises of primitives, Map and List.
以下示例说明了上述概念。
Following example illustrates the above concept.
Example
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.json.simple.JSONValue;
class JsonDemo {
public static void main(String[] args) throws IOException {
Map m1 = new LinkedHashMap();
m1.put("k11","v11");
m1.put("k12","v12");
m1.put("k13", "v13");
List l1 = new LinkedList();
l1.add(m1);
l1.add(new Integer(100));
String jsonString = JSONValue.toJSONString(l1);
System.out.println(jsonString);
}
}
JSON.simple - Primitive, Object, Map, List
使用 JSONValue 对象,我们可以创建一个包含基本类型、对象、映射和列表的 JSON。
Using JSONValue object, we can create a JSON which comprises of primitives, Object, Map and List.
以下示例说明了上述概念。
Following example illustrates the above concept.
Example
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
class JsonDemo {
public static void main(String[] args) throws IOException {
JSONObject obj = new JSONObject();
Map m1 = new LinkedHashMap();
m1.put("k11","v11");
m1.put("k12","v12");
m1.put("k13", "v13");
List l1 = new LinkedList();
l1.add(new Integer(100));
obj.put("m1", m1);
obj.put("l1", l1);
String jsonString = JSONValue.toJSONString(obj);
System.out.println(jsonString);
}
}
JSON.simple - Customized Output
我们可以根据自定义类定制 JSON 输出。唯一的需求是实现 JSONAware 接口。
We can customize JSON output based on custom class. Only requirement is to implement JSONAware interface.
以下示例说明了上述概念。
Following example illustrates the above concept.
Example
import java.io.IOException;
import org.json.simple.JSONArray;
import org.json.simple.JSONAware;
import org.json.simple.JSONObject;
class JsonDemo {
public static void main(String[] args) throws IOException {
JSONArray students = new JSONArray();
students.add(new Student(1,"Robert"));
students.add(new Student(2,"Julia"));
System.out.println(students);
}
}
class Student implements JSONAware {
int rollNo;
String name;
Student(int rollNo, String name){
this.rollNo = rollNo;
this.name = name;
}
@Override
public String toJSONString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
sb.append("name");
sb.append(":");
sb.append("\"" + JSONObject.escape(name) + "\"");
sb.append(",");
sb.append("rollNo");
sb.append(":");
sb.append(rollNo);
sb.append("}");
return sb.toString();
}
}
JSON.simple - Customized Output Streaming
我们可以根据自定义类定制 JSON 流输出。唯一的需求是实现 JSONStreamAware 接口。
We can customize JSON streaming output based on custom class. Only requirement is to implement JSONStreamAware interface.
以下示例说明了上述概念。
Following example illustrates the above concept.
Example
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.LinkedHashMap;
import java.util.Map;
import org.json.simple.JSONArray;
import org.json.simple.JSONStreamAware;
import org.json.simple.JSONValue;
class JsonDemo {
public static void main(String[] args) throws IOException {
JSONArray students = new JSONArray();
students.add(new Student(1,"Robert"));
students.add(new Student(2,"Julia"));
StringWriter out = new StringWriter();
students.writeJSONString(out);
System.out.println(out.toString());
}
}
class Student implements JSONStreamAware {
int rollNo;
String name;
Student(int rollNo, String name){
this.rollNo = rollNo;
this.name = name;
}
@Override
public void writeJSONString(Writer out) throws IOException {
Map obj = new LinkedHashMap();
obj.put("name", name);
obj.put("rollNo", new Integer(rollNo));
JSONValue.writeJSONString(obj, out);
}
}