1.导入pom.xml文件
<dependencies>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.59</version>
</dependency>
</dependencies>
2.创建对象Person
import java.io.Serializable;
public class Person {
private int id;
private String name;
private int age;
private String gender;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}
3.java对象,json对象,字符串之间相互转化
1.java对象转化为JSON字符串
String userString = JSON.toJSONString(User);
2.JSON字符串转换为java对象
User user = JSON.parseJSON(userString,User.class);
3.JSON字符串转化为JSON对象
JSON userJson = (JSON)JSON.parseJSON(userString);
4.JSON对象转化为JSON字符串
String userString = JSON.toJSONString(userJson);
5.JAVA对象转化为JSON对象
JSON userJson = (JSON)JSON.toJSON(user);
6.JSON对象转化为JAVA对象
User user = JSON.toJavaObject(userJson);