On parsing and generating JSON using java
JSON overview
JSON, namely JavaScript object notation, is a subset of JavaScript object notation. It has the following characteristics:
Data is placed in key value pairs; Data is separated by commas; Curly braces represent objects; Square brackets represent arrays.
JSON values can be:
Number (integer or floating point number) string (in double quotation marks) logical value (true or false) array (in square brackets) object (in curly brackets) null
Basic syntax of JSON
JSON object
JSON objects are written in curly braces. The object can contain multiple key value pairs, for example:
JSON array
JSON arrays are written in square brackets. The array can contain multiple objects, for example:
In the above example, the root curly bracket indicates that this is a JSON object, the key of this object is employees, and the value is a JSON array. There are three JSON objects in this array, and each JSON object is separated by commas.
Reading JSON data using java
On the JSON official website, we can see the support of various grammars for JSON. For Java, the more mature one is Google gson.
Its Maven dependencies are as follows:
Now write a program to parse the following test json:
The following code will parse the above JSON data:
Generating JSON data using java
The key to generating JSON data is the add and addproperty methods in JSON objects. The former is used to add an array or another JSON object to the JSON object, and the latter is used to add properties to the JSON object. The following code will generate the test in the above example json。
I use org. Net to construct and parse JSON in Java JSON, the following are two functions: one is to create JSON, and the other is to construct JSON from text and parse it.
Create JSON
Parsing JSON
It is quite convenient to handle JSON in Java.