1. Overview
1.概述
JSON (JavaScript Object Notation) is a lightweight data-interchange format, and we most commonly use it for client-server communication. It’s both easy to read/write and language-independent. A JSON value can be another JSON object, array, number, string, boolean (true/false) or null.
JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,我们最常使用它进行客户端-服务器通信。它既容易读/写,又与语言无关。一个JSON值可以是另一个JSON对象、数组、数字、字符串、布尔(真/假)或空。
In this tutorial, we’ll see how to create, manipulate and parse JSON using one of the available JSON processing libraries — JSON-Java library, also known as org.json.
在本教程中,我们将看到如何使用现有的JSON处理库之一–JSON-Java库,也称为org.json来创建、操作和解析JSON。
2. Prerequisite
2.先决条件
We’ll first need to add the following dependency in our pom.xml:
我们首先需要在我们的pom.xml中添加以下依赖性。
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20180130</version>
</dependency>
The latest version can be found in the Maven Central Repository.
最新版本可以在Maven中央仓库中找到。
Note that this package has already been included in Android SDK, so we shouldn’t include it while using the same.
注意,这个包已经包含在Android SDK中,所以我们在使用时不应该包含它。
3. JSON in Java [package org.json]
3.Java中的JSON[包org.json]
The JSON-Java library also known as org.json (not to be confused with Google’s org.json.simple) provides us with classes that are used to parse and manipulate JSON in Java.
JSON-Java库也被称为org.json(不要与Google的org.json.simple混淆)为我们提供了用于在Java中解析和操作JSON的类。
Furthermore, this library can also convert between JSON, XML, HTTP Headers, Cookies, Comma Delimited List or Text, etc.
此外,这个库还可以在JSON、XML、HTTP头文件、Cookies、逗号分隔的列表或文本等之间进行转换。
In this tutorial, we’ll have a look at the following classes:
在本教程中,我们将看一下以下类。
- JSONObject – similar to Java’s native Map-like object, which stores unordered key-value pairs
- JSONArray – an ordered sequence of values similar to Java’s native Vector implementation
- JSONTokener – a tool that breaks a piece of text into a series of tokens that can be used by JSONObject or JSONArray to parse JSON strings
- CDL – a tool that provides methods to convert comma delimited text into a JSONArray and vice versa
- Cookie – converts from JSON String to cookies and vice versa
- HTTP – used to convert from JSON String to HTTP headers and vice versa
- JSONException – a standard exception thrown by this library
4. JSONObject
4.JSONObject
A JSONObject is an unordered collection of key and value pairs, resembling Java’s native Map implementations.
一个JSONObject是一个无序的键和值对的集合,类似于Java的本地Map实现。
- Keys are unique Strings that cannot be null.
- Values can be anything from a Boolean, Number, String, or JSONArray to even a JSONObject.NULL object.
- A JSONObject can be represented by a String enclosed within curly braces with keys and values separated by a colon, and pairs separated by a comma.
- It has several constructors with which to construct a JSONObject.
It also supports the following main methods:
它还支持以下主要方法。
- get(String key) – gets the object associated with the supplied key, throws JSONException if the key is not found
- opt(String key) – gets the object associated with the supplied key, null otherwise
- put(String key, Object value) – inserts or replaces a key-value pair in current JSONObject.
The put() method is an overloaded method that accepts a key of type String and multiple types for the value.
put() 方法是一个重载方法,它接受一个String类型的键和多种类型的值。
For the complete list of methods supported by JSONObject, visit the official documentation.
对于JSONObject所支持的方法的完整列表,访问官方文档。。
Let’s now discuss some of the main operations supported by this class.
现在让我们来讨论这个类所支持的一些主要操作。
4.1. Creating JSON Directly From JSONObject
4.1.直接从JSONObject创建JSON
JSONObject exposes an API similar to Java’s Map interface.
JSONObject暴露了一个类似于Java的Map接口的API.。
We can use the put() method and supply the key and value as an argument:
我们可以使用put()方法并提供key和value作为参数。
JSONObject jo = new JSONObject();
jo.put("name", "jon doe");
jo.put("age", "22");
jo.put("city", "chicago");
Now our JSONObject would look like this:
现在我们的JSONObject将看起来像这样。
{"city":"chicago","name":"jon doe","age":"22"}
There are seven different overloaded signatures of JSONObject.put() method. While the key can only be unique, non-null String, the value can be anything.
JSONObject.put()方法有七个不同的重载签名。虽然键只能是唯一的、非空的String,但值可以是任何东西。
4.2. Creating JSON From Map
4.2.从地图创建JSON
Instead of directly putting key and values in a JSONObject, we can construct a custom Map and then pass it as an argument to JSONObject‘s constructor.
我们可以构建一个自定义的Map,然后将其作为参数传递给JSONObject的构造函数,而不是直接将key和value放入JSONObject。
This example will produce same results as above:
这个例子将产生与上述相同的结果。
Map<String, String> map = new HashMap<>();
map.put("name", "jon doe");
map.put("age", "22");
map.put("city", "chicago");
JSONObject jo = new JSONObject(map);
4.3. Creating JSONObject From JSON String
4.3.从JSON String创建JSONObject
To parse a JSON String to a JSONObject, we can just pass the String to the constructor.
要将JSONString解析为JSONObject,我们只需将String传递给构造函数。
This example will produce same results as above:
这个例子将产生与上述相同的结果。
JSONObject jo = new JSONObject(
"{\"city\":\"chicago\",\"name\":\"jon doe\",\"age\":\"22\"}"
);
The passed String argument must be a valid JSON; otherwise, this constructor may throw a JSONException.
传递的String参数必须是有效的JSON;否则,这个构造函数可能会抛出一个JSONException。
4.4. Serialize Java Object to JSON
4.4.将Java对象序列化为JSON
One of JSONObject’s constructors takes a POJO as its argument. In the example below, the package uses the getters from the DemoBean class and creates an appropriate JSONObject for the same.
JSONObject的构造函数之一需要一个POJO作为它的参数。在下面的例子中,包使用来自DemoBean类的getters,并为其创建一个适当的JSONObject。
To get a JSONObject from a Java Object, we’ll have to use a class that is a valid Java Bean:
为了从一个Java对象中获得一个JSONObject,我们必须使用一个有效的Java Bean类。
DemoBean demo = new DemoBean();
demo.setId(1);
demo.setName("lorem ipsum");
demo.setActive(true);
JSONObject jo = new JSONObject(demo);
And here’s the JSONObject jo:
而这里是JSONObject jo。
{"name":"lorem ipsum","active":true,"id":1}
Although we have a way to serialize a Java object to JSON string, there is no way to convert it back using this library. If we want that kind of flexibility, we can switch to other libraries such as Jackson.
虽然我们有办法将一个Java对象序列化为JSON字符串,但没有办法使用这个库将其转换回来。如果我们想要这样的灵活性,我们可以切换到其他库,比如Jackson。
5. JSONArray
5.JSONArray
A JSONArray is an ordered collection of values, resembling Java’s native Vector implementation.
一个JSONArray是一个有序的值集合,类似于Java的本地 Vector实现。。
- Values can be anything from a Number, String, Boolean, JSONArray, or JSONObject to even a JSONObject.NULL object.
- It’s represented by a String wrapped within square brackets and consists of a collection of values separated by commas.
- Like JSONObject, it has a constructor that accepts a source String and parses it to construct a JSONArray.
These are the primary methods of the JSONArray class:
这些是JSONArray类的主要方法。
- get(int index) – returns the value at the specified index (between 0 and total length – 1), otherwise throws a JSONException
- opt(int index) – returns the value associated with an index (between 0 and total length – 1). If there’s no value at that index, then a null is returned.
- put(Object value) – append an object value to this JSONArray. This method is overloaded and supports a wide range of data types.
For a complete list of methods supported by JSONArray, visit the official documentation.
关于JSONArray支持的方法的完整列表,请访问官方文档。
5.1. Creating JSONArray
5.1.创建JSONArray
Once we’ve initialized a JSONArray object, we can simply add and retrieve elements using the put() and get() methods:
一旦我们初始化了JSONArray对象,我们就可以使用put()和get()方法简单地添加和检索元素。
JSONArray ja = new JSONArray();
ja.put(Boolean.TRUE);
ja.put("lorem ipsum");
JSONObject jo = new JSONObject();
jo.put("name", "jon doe");
jo.put("age", "22");
jo.put("city", "chicago");
ja.put(jo);
Following are the contents of our JSONArray (code is formatted for clarity):
以下是我们的JSONArray的内容(为了清晰起见,代码是有格式的)。
[
true,
"lorem ipsum",
{
"city": "chicago",
"name": "jon doe",
"age": "22"
}
]
5.2. Creating JSONArray Directly From JSON String
5.2.直接从JSON字符串创建JSONArray
Like JSONObject, the JSONArray also has a constructor that creates a Java object directly from a JSON String:
与JSONObject一样,JSONArray也有一个构造函数,可以直接从JSONString创建一个Java对象。
JSONArray ja = new JSONArray("[true, \"lorem ipsum\", 215]");
This constructor may throw a JSONException if the source String isn’t a valid JSON String.
如果源String不是一个有效的JSONString,这个构造函数可能会抛出一个JSONException。
5.3. Creating JSONArray Directly From a Collection or an Array
5.3.直接从一个集合或数组中创建JSONArray
The constructor of JSONArray also supports collection and array objects as arguments.
JSONArray的构造函数也支持集合和数组对象作为参数。
We simply pass them as an argument to the constructor, and it will return a JSONArray object:
我们只需将它们作为一个参数传递给构造函数,它将返回一个JSONArray对象。
List<String> list = new ArrayList<>();
list.add("California");
list.add("Texas");
list.add("Hawaii");
list.add("Alaska");
JSONArray ja = new JSONArray(list);
Now our JSONArray consists of the following:
现在我们的JSONArray由以下内容组成。
["California","Texas","Hawaii","Alaska"]
6. JSONTokener
6.JSONTokener
A JSONTokener takes a source String as input to its constructor and extracts characters and tokens from it. It’s used internally by classes of this package (like JSONObject, JSONArray) to parse JSON Strings.
JSONTokener将一个源String作为其构造函数的输入,并从中提取字符和标记物。它被这个包的类(如JSONObject, JSONArray)内部使用,以解析JSON Strings。
There may not be many situations where we’ll directly use this class since we can achieve the same functionality using other simpler methods (like string.toCharArray()):
我们直接使用这个类的情况可能不多,因为我们可以用其他更简单的方法(比如string.toCharArray())实现同样的功能。
JSONTokener jt = new JSONTokener("lorem");
while(jt.more()) {
Log.info(jt.next());
}
Now we can access a JSONTokener like an iterator, using the more() method to check if there are any remaining elements and next() to access the next element.
现在我们可以像一个迭代器一样访问一个JSONTokener,使用more()方法来检查是否有任何剩余的元素,以及next()来访问下一个元素。
Here are the tokens received from the previous example:
下面是前一个例子中收到的代币。
l
o
r
e
m
7. CDL
7.CDL
We’re provided with a CDL (Comma Delimited List) class to convert comma delimited text into a JSONArray and vice versa.
我们获得了一个CDL(逗号分隔的列表)类,用于将逗号分隔的文本转换成JSONArray,反之亦然。
7.1. Producing JSONArray Directly From Comma Delimited Text
7.1.直接从逗号分隔的文本中产生JSONArray
In order to produce a JSONArray directly from the comma delimited text, we can use the static method rowToJSONArray(), which accepts a JSONTokener:
为了直接从逗号分隔的文本中产生一个JSONArray,我们可以使用静态方法rowToJSONArray(),它接受一个JSONTokener。
JSONArray ja = CDL.rowToJSONArray(new JSONTokener("England, USA, Canada"));
Here’s what our JSONArray consists of now:
下面是我们的JSONArray现在的组成。
["England","USA","Canada"]
7.2. Producing Comma Delimited Text From JSONArray
7.2.从JSONArray中产生以逗号分隔的文本
Let’s see how to reverse of the previous step and get back the comma delimited text from JSONArray:
让我们看看如何颠覆上一步,从JSONArray中取回逗号分隔的文本。
JSONArray ja = new JSONArray("[\"England\",\"USA\",\"Canada\"]");
String cdt = CDL.rowToString(ja);
The String cdt now contains the following:
字符串 cdt现在包含以下内容。
England,USA,Canada
7.3. Producing JSONArray of JSONObjects Using Comma Delimited Text
7.3.使用逗号分隔的文本产生JSONArray的JSONObjects
To produce a JSONArray of JSONObjects, we’ll use a text String containing both headers and data separated by commas.
为了产生一个JSONArray的JSONObjects,我们将使用一个文本String,包含标题和数据,用逗号分隔。
We separate the different lines using a carriage return (\r) or line feed (\n).
我们用回车(\r)或换行(\n)分隔不同的行。
The first line is interpreted as a list of headers, and all the subsequent lines are treated as data:
第一行被解释为标题列表,所有后续行被视为数据。
String string = "name, city, age \n" +
"john, chicago, 22 \n" +
"gary, florida, 35 \n" +
"sal, vegas, 18";
JSONArray result = CDL.toJSONArray(string);
The object JSONArray result now consists of the following (output formatted for the sake of clarity):
对象JSONArray result 现在由以下内容组成(为清晰起见,输出格式化)。
[
{
"name": "john",
"city": "chicago",
"age": "22"
},
{
"name": "gary",
"city": "florida",
"age": "35"
},
{
"name": "sal",
"city": "vegas",
"age": "18"
}
]
Notice that both data and header were supplied within the same String. We have an alternative way of doing this where we can achieve the same functionality by supplying a JSONArray to get the headers and a comma delimited String working as the data.
请注意,数据和标题都是在同一个String中提供的。我们有一个替代方法,我们可以通过提供一个JSONArray来实现相同的功能,以获得标题和一个逗号分隔的String作为数据。
Again, we separate different lines using a carriage return (\r) or line feed (\n):
同样,我们用回车(\r)或换行(\n)来分隔不同的行。
JSONArray ja = new JSONArray();
ja.put("name");
ja.put("city");
ja.put("age");
String string = "john, chicago, 22 \n"
+ "gary, florida, 35 \n"
+ "sal, vegas, 18";
JSONArray result = CDL.toJSONArray(ja, string);
Here we’ll get the contents of object result exactly as before.
在这里,我们将获得对象result的内容,与之前的完全一样。
8. Cookie
8.饼干
The Cookie class deals with web browser cookies and has methods to convert a browser cookie into a JSONObject and vice versa.
Cookie类处理网络浏览器的cookie,并有方法将浏览器cookie转换成JSONObject,反之亦然。
Here are the main methods of the Cookie class:
下面是Cookie类的主要方法。
- toJsonObject(String sourceCookie) – converts a cookie string into a JSONObject
- toString(JSONObject jo) – reverse of the previous method, converts a JSONObject into a cookie String
8.1. Converting a Cookie String into a JSONObject
8.1.将Cookie的字符串转换为JSONObject
To convert a cookie String to a JSONObject, we’ll use the static method Cookie.toJSONObject():
为了将一个cookie String转换为JSONObject,我们将使用静态方法Cookie.toJSONObject()。
String cookie = "username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/";
JSONObject cookieJO = Cookie.toJSONObject(cookie);
8.2. Converting a JSONObject into Cookie String
8.2.将JSONObject转换为Cookie String
Now we’ll convert a JSONObject into cookie String. This is the reverse of the previous step:
现在我们将把一个JSONObject转换为cookieString。这是上一步的反向步骤。
String cookie = Cookie.toString(cookieJO);
9. HTTP
9.HTTP
The HTTP class contains static methods that are used to convert HTTP headers to JSONObject and vice versa.
HTTP类包含静态方法,用于将HTTP头文件转换成JSONObject,反之亦然。
This class also has two main methods:
该类也有两个主要方法。
- toJsonObject(String sourceHttpHeader) – converts a HttpHeader String to JSONObject
- toString(JSONObject jo) – converts the supplied JSONObject to String
9.1. Converting JSONObject to HTTP Header
9.1.将JSONObject转换为HTTP标头
HTTP.toString() method is used to convert a JSONObject to HTTP header String:
HTTP.toString()方法用于将JSONObject转换成HTTP头String。
JSONObject jo = new JSONObject();
jo.put("Method", "POST");
jo.put("Request-URI", "http://www.example.com/");
jo.put("HTTP-Version", "HTTP/1.1");
String httpStr = HTTP.toString(jo);
Here is what our String httpStr will consist of:
以下是我们的String httpStr将包括的内容。
POST "http://www.example.com/" HTTP/1.1
Note that while converting an HTTP request header, the JSONObject must contain “Method”, “Request-URI” and “HTTP-Version” keys. And for response header, the object must contain “HTTP-Version”, “Status-Code” and “Reason-Phrase” parameters.
请注意,在转换HTTP请求头时,JSONObject必须包含“Method”、“Request-URI”和“HTTP-Version”键。而对于响应头,该对象必须包含“HTTP-Version”、“Status-Code”和“Reason-Phrase”参数。
9.2. Converting HTTP Header String Back to JSONObject
9.2.将HTTP报头String转换回JSONObject
Here we will convert the HTTP string that we got in the previous step back to the very JSONObject we created in that step:
在这里,我们将把上一步得到的HTTP字符串转换为我们在那一步创建的JSONObject。
JSONObject obj = HTTP.toJSONObject("POST \"http://www.example.com/\" HTTP/1.1");
10. JSONException
10.JSONException
The JSONException is the standard exception thrown by this package whenever any error is encountered.
JSONException是该包在遇到任何错误时抛出的标准异常。
This is used across all classes from this package. The exception is usually followed by a message that states what exactly went wrong.
这将在这个包的所有类中使用。异常后面通常会有一条信息,说明到底是什么地方出了问题。
11. Conclusion
11.结论
In this article, we looked at a JSON using Java — org.json — and we focused on some of the core functionality available here.
在这篇文章中,我们看了一个使用Java的JSON–org.json–我们着重于这里的一些核心功能。
The complete code snippets used in this article can be found over on GitHub.
本文中使用的完整代码片段可以在GitHub上找到over。