JSON
1, What is JSON?
The full name of JSON is JavaScript object notation. JavaScript object notation is a data structure that replaces XML. Now JSON is mostly used to store and exchange the syntax of text information for data transmission. JSON is smaller, faster and easier to parse than XML. Moreover, the JSON parser and JSON library support many different programming languages.
2, Syntax:
Basic rules
Data in name / value pairs: json data consists of key value pairs
-
Keys and values can be enclosed in quotation marks (either single or double), or keys can be enclosed without quotation marks
-
Value type:
- Number (integer or floating point number)
- String (in double quotes)
- Logical value (true or false)
- Array (in square brackets) {"persons": [{}, {}]}
- Object (in curly braces) {"address": {"province": "Heilongjiang"...}}
- null
-
Data is separated by commas: multiple key value pairs are separated by commas
-
Curly brace save object: use {} to define json format
-
Square bracket save array: []
-
: a colon indicates that the latter is the value of the former (this value can be a string, a number, or another array or object)
For example:
"result":{ "year":2002, "month":11, "day":9, "Animal":"horse", "IDayCn":"ninth day of a lunar month", "ncWeek":"Thursday", "astro":"sagittarius", "fiveAll":{ "five":["Water and fire","Water water","Wood","Golden fire"], "lose":"Soil" } }
result represents a json object, where year and month are its attributes, and five represents an array in which json objects can be nested.
3, How to parse JSON
JSON parser:
Common parsers: Jsonlib, Gson, fastjson and jackson. Only Gson and fastjson are introduced here.
1. Use Gson parsing
First, introduce the dependency of Gsonjar package
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.8</version> </dependency>
JSON object to Java object
Directly create a Gson object and call the toJson method of its object to parse a Java object into a JSON object
Gson gson = new Gson(); Book book = new Book(); book.setId("100"); book.setName("Brief history of time"); book.setInfo("Quantum physics"); //Object conversion json String json = gson.toJson(book); System.out.println(json );
Output as
{"id":"100","name":"Brief history of time","info":"Quantum physics"}
Turn JSON into a Java object and call its fromJson method
//json conversion object String json = "{\"id\":\"100\",\"name\":\"Brief history of time\",\"info\":\"Quantum physics\"}"; Book book1 = gson.fromJson(json, Book.class); System.out.println(book1);
Output as
Book{id='100', name='Brief history of time', info='Quantum physics'}
You can also convert JSON to HashMap type
String json = "{\"id\":\"100\",\"name\":\"Brief history of time\",\"info\":\"Quantum physics\"}"; HashMap hashMap = gson.fromJson(json, HashMap.class); System.out.println(hashMap);
Output as
{name=Brief history of time, id=100, info=Quantum physics}
If there is an array type in a JSON object, Gson will automatically convert it to an ArrayList array
For example, the previous example
String s = "{\"five\":[\"Water and fire\",\"Water water\",\"Wood\",\"Golden fire\"],\"lose\":\"Soil\"}"; HashMap hashMap = gson.fromJson(s, HashMap.class); System.out.println(hashMap);
Output as
{lose=Soil, five=[Water and fire, Water water, Wood, Golden fire]}
2. Use fastjson to parse
First, introduce dependencies
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.78</version> </dependency>
Convert a Java object into a JSON object, and directly call the static method toJSONString() of the JSON object to pass in the Java object to be converted
Book book = new Book(); book.setId("10086"); book.setName("The Great Gatsby"); book.setInfo("A tragic love story"); //Object to json String s = JSON.toJSONString(book); System.out.println(s);
Output is:
{"id":"10086","info":"A tragic love story","name":"The Great Gatsby"}
Similarly, it is the same for converting JSON objects to Java, calling its parse method or parseObject method
//json to object Book object = JSON.parseObject("{\"id\":\"10086\",\"info\":\"A tragic love story\",\"name\":\"The Great Gatsby\"}", Book.class); System.out.println(object); Object parse = JSON.parse("[ \"Porsche\", \"BMW\", \"Volvo\" ]"); System.out.println(parse);
Output:
Book{id='10086', name='The Great Gatsby', info='A tragic love story'} ["Porsche","BMW","Volvo"]
The second parameter of the parseObject method can pass in different types of class objects to get the desired type
HashMap hashMap = JSON.parseObject("{\"id\":\"10086\",\"info\":\"A tragic love story\",\"name\":\"The Great Gatsby\"}", HashMap.class); System.out.println(hashMap);
Output:
{name=The Great Gatsby, id=10086, info=A tragic love story}
There are many API s for the conversion between JSON and Java objects, and only simple usage is introduced here.