3.3 Mutual conversion between JSON string and Java object
After learning json, let's talk about the role of json.
In the future, we will use data in json format for front-end and back-end interactions. When the front end sends a request, if it is complex data, it will submit it to the back end in json; and if the back end needs to respond to some complex data, it also needs to respond the data back to the browser in json format.
At the back end, we need to focus on learning the following two parts of the operation:
-
Request data: Convert JSON string to Java object
-
Response data: Java object converted to JSON string
Next, I will introduce a set of API to you, which can realize the above two operations. This API isFastjson
3.3.1 Fastjson overview
Fastjson
It is a high-performance and fully functional JSON
library written in Java language provided by Alibaba. It is currently the fastest JSON
library in Java language, which can realize the mutual conversion between Java
objects and strings.JSON
3.3.2 Using Fastjson
Fastjson
The use is also relatively simple, divided into the following three steps to complete
1. Import coordinates
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
2. Java object to JSON
String jsonStr = JSON.toJSONString(obj);
To convert a Java object to a JSON string, you only need to use the static methods in the Fastjson
provided class.JSON
toJSONString()
3. Convert JSON string to Java object
User user = JSON.parseObject(jsonStr, User.class);
To convert json to Java object, you only need to use the static method in the Fastjson
provided class.JSON
parseObject()
3.3.3 Code Demonstration
-
import coordinates
-
Create a class specially used to test the conversion between Java objects and JSON strings, the code is as follows:
public class FastJsonDemo {
public static void main(String[] args) {
//1. 将Java对象转为JSON字符串
User user = new User();
user.setId(1);
user.setUsername("zhangsan");
user.setPassword("123");
String jsonString = JSON.toJSONString(user);
System.out.println(jsonString);//{"id":1,"password":"123","username":"zhangsan"}
//2. 将JSON字符串转为Java对象
User u = JSON.parseObject("{\"id\":1,\"password\":\"123\",\"username\":\"zhangsan\"}", User.class);
System.out.println(u);
}
}