fastjson的详细用法
1. 作用:
fastjson用于将Java Bean序列化为JSON字符串,也可以从JSON字符串反序列化到JavaBean。
2. 导入依赖:
<dependencies>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.49</version>
</dependency>
</dependencies>
3 、创建一个java bean,注意属性一定要有get和set
package com.cw.weblog.bean;
public class Student {
private Integer id;
private String name;
private String date;
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public java.lang.String getName() {
return name;
}
public void setName(java.lang.String name) {
this.name = name;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
4. 用法一
讲java bean对象转化为json字符串
public static void main(String[] args) {
Student student = new Student();
student.setId(1);
student.setName("张三");
String studentJson = JSON.toJSONString(student);
System.out.println(studentJson);
}
运行结果:
从上图中可以看到,没有赋值的属性就没有被转化成json,这可能不是我们想要的于是我们做了一下改造
public static void main(String[] args) {
Student student = new Student();
student.setId(1);
student.setName("张三");
String studentJson = JSON.toJSONString(student,
SerializerFeature.WriteNullStringAsEmpty);
System.out.println(studentJson);
}
5、虽然已经转化成json字符串了,但是看起来并不像,我们可以规范格式
public static void main(String[] args) {
Student student = new Student();
student.setId(1);
student.setName("张三");
String studentJson = JSON.toJSONString(student, SerializerFeature.PrettyFormat,
SerializerFeature.WriteNullStringAsEmpty);
System.out.println(studentJson);
}
6. 用法二
1、将json字符串转化成java bean
public static void main(String[] args) {
String jsonString = "{\"id\":1,\"name\":\"张三\",\"date\":\"2021-12-02\"}";
Student user = JSON.parseObject(jsonString, Student.class);
System.out.println(user.getDate());
System.out.println(user.getName());
}