FastJson

将JSON字符串转换成Java类的工具类

1.添加依赖

  • 在pom文件添加依赖
  1. <dependency>
  2. <groupId>com.alibaba</groupId>
  3. <artifactId>fastjson</artifactId>
  4. <version>1.2.75</version>
  5. </dependency>

2. 对象转JSON

  • 将 Java 对象转换为 JSON 格式
  1. @Data
  2. public class Person {
  3. private String name;
  4. private int age;
  5. }
  1. Person p = new Person("hzlim",15);
  2. String s = JSON.toJSONString(p);
  • 可以通过过滤器来设置转换的字段
  1. SimplePropertyPreFilter filter = new SimplePropertyPreFilter(Person.class, "name");
  2. String s = JSON.toJSONString(p, filter);

3.JSON转对象

  • 将JSON字符串转为Java对象
  1. String json = "{"age":11,"name":"hzlim"}";
  2. Person person = JSON.parseObject(json, Person.class);

4.JSON转对象集合

  • 将JSON字符串转换为对象集合
  1. String json = "[{"age":11,"name":"hzlim"}]";
  2. List<Person> people = JSON.parseArray(",", Person.class);

5.@JSONField注解

  • name属性:字段的名称
  • ordinal属性:指定字段的顺序
  • serialize属性:指定字段不序列化
  1. @Data
  2. public class Person {
  3. @JSONField(name="NAME",ordinal = 1)
  4. private String name;
  5. @JSONField(name="AGE",ordinal = 2)
  6. private int age;
  7. @JSONField(serialize = false)
  8. private String birthday;
  9. }

更新时间:{docsify-updated}