1.fastJson说明
fastjson是阿里巴巴的开源JSON解析库,它可以解析JSON格式的字符串,
支持将Java Bean序列化为JSON字符串,也可以从JSON字符串反序列化到JavaBean。
2.fastJson特点
fastjson相对其他JSON库的特点是快,fastjson的API十分简洁。
3.springboot工程中使用,引入maven
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.32</version>
</dependency>
4.序列化一个对象成 JSON 字符串
新建一个People实体
@Data
public class People {
private String name;
private Date birth;
private int age;
private String sex;
private List<People> children;
}
将People序列化
/**
* 序列化一个对象成json字符串
* @param args
*/
public static void main(String[] args) {
People people = new People();
people.setAge(30);
people.setBirth(new Date());
people.setName("大明");
people.setSex("男");
ArrayList<People> children = new ArrayList<>();
for (int i=0 ; i<2 ; i++){
People son = new People();
son.setAge(6+i);
son.setBirth(new Date());
son.setName("小红");
son.setSex("女");
children.add(son);
}
people.setChildren(children);
System.out.println(JSON.toJSONString(people));
}
输出结果,我放到JsonHandle
5.反序列化一个 JSON 字符串成 Java 对象
使用刚才输出的json字符串,反序列化成People对象
public static void main(String[] args) {
String json = "{\"age\":30,\"birth\":1589942848442," +
"\"children\":[{\"age\":6,\"birth\":1589942848442,\"name\":\"小红\",\"sex\":\"女\"}," +
"{\"age\":7,\"birth\":1589942848442,\"name\":\"小红\",\"sex\":\"女\"}]," +
"\"name\":\"大明\",\"sex\":\"男\"}";
People people = JSON.parseObject(json, People.class);
System.out.println(people.toString());
}
输出结果
6.日期处理
@Data
public class People {
private String name;
@JSONField(format = "yyyy-MM-dd hh:mm:ss")
private Date birth;
private int age;
private String sex;
private List<People> children;
}
输出结果