FastJson
将JSON字符串转换成Java类的工具类
1.添加依赖
- 在pom文件添加依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.75</version>
</dependency>
2. 对象转JSON
- 将 Java 对象转换为 JSON 格式
@Data
public class Person {
private String name;
private int age;
}
Person p = new Person("hzlim",15);
String s = JSON.toJSONString(p);
- 可以通过过滤器来设置转换的字段
SimplePropertyPreFilter filter = new SimplePropertyPreFilter(Person.class, "name");
String s = JSON.toJSONString(p, filter);
3.JSON转对象
- 将JSON字符串转为Java对象
String json = "{"age":11,"name":"hzlim"}";
Person person = JSON.parseObject(json, Person.class);
4.JSON转对象集合
- 将JSON字符串转换为对象集合
String json = "[{"age":11,"name":"hzlim"}]";
List<Person> people = JSON.parseArray(",", Person.class);
5.@JSONField注解
name
属性:字段的名称ordinal
属性:指定字段的顺序serialize
属性:指定字段不序列化
@Data
public class Person {
@JSONField(name="NAME",ordinal = 1)
private String name;
@JSONField(name="AGE",ordinal = 2)
private int age;
@JSONField(serialize = false)
private String birthday;
}
更新时间:{docsify-updated}