我可不是为了被全人类喜欢才活着的,只|

王陸

园龄:6年11个月粉丝:2052关注:178

fastjson2 简单使用

参考

https://alibaba.github.io/fastjson2/
https://alibaba.github.io/fastjson2/annotations_cn.html
https://alibaba.github.io/fastjson2/features_cn

基本操作

json 字符串转为 jsonObject:

String json = "{\"name\":\"tom\",\"age\":18}";
JSONObject data = JSON.parseObject(json);

json 字符串转为 jsonArray:

String json = "[{\"name\":\"Alice\",\"age\":25,\"city\":\"Exampleville\"},{\"name\":\"Bob\",\"age\":30," +
        "\"city\":\"Sampleburg\"},{\"name\":\"Charlie\",\"age\":28,\"city\":\"Testington\"}]";
JSONArray jsonArray = JSON.parseArray(json);

json 字符串转为 JavaBean 对象:

String json = "{\"name\":\"tom\",\"age\":18}";
User user = JSON.parseObject(json, User.class);

java 对象转为 json 字符串:

User user = new User();
user.setName("tom");
user.setAge(18);
String jsonString = JSON.toJSONString(user);

操作 json,获取简单属性:

String json = "{\"name\":\"JohnDoe\",\"age\":30,\"city\":\"NewYork\",\"isStudent\":false,\"grades\":[85,90," +
        "78,92],\"address\":{\"street\":\"123MainSt\",\"zipCode\":\"10001\"},\"contact\":{\"email\":\"john" +
        ".doe@example.com\",\"phoneNumbers\":[\"555-1234\",\"555-5678\"]},\"balance\":1200.75}";
JSONObject jsonObject = JSON.parseObject(json);
String name = jsonObject.getString("name");
Integer age = jsonObject.getInteger("age");
JSONArray grades = jsonObject.getJSONArray("grades");
Object o = grades.get(0);
JSONObject address = jsonObject.getJSONObject("address");
String street = address.getString("street");
Double balance = jsonObject.getDouble("balance");

fastjson2 中提供了 json 中对象和数组的对应表示,对象使用 JSONObject 表示,列表使用 JSONArray 表示,JSONObject、JSONArray 也都提供了相应的操作方法来实现获取值、添加值、更新值、删除值等操作(方法都很通俗易懂,get 开头就是获取值,set 开头的方法就是更新值,方法名和 remove 类似的就是删除操作,非常简单)。

高级操作

枚举类序列化时指定序列化使用的字段

第一种实现方法比较复杂,是使用自定义序列化器实现:

@Getter
public enum Season {
    SPRING("春天", "万物复苏"),
    SUMMER("夏天", "热"),
    AUTUMN("秋天", "秋高气爽"),
    WINTER("冬季", "冷");

    private final String description;

    private final String features;

    Season(String description, String features) {
        this.description = description;
        this.features = features;
    }
}
@Data
public class Student {
    public String name;
    public Integer age;
    public Season favoriteSeason;
}
// enum 默认序列化成 json
Student student = new Student();
student.setAge(18);
student.setName("tom");
student.setFavoriteSeason(Season.SUMMER);
System.out.println(JSON.toJSONString(student));

// 使用序列化器指定枚举类序列化时使用的字段
final ObjectWriter<Season> seasonWriter = (jsonWriter, fieldValue, fieldName, type, l) -> {
    if (fieldValue instanceof Season) {
        jsonWriter.writeString(((Season) fieldValue).getDescription());
    } else {
        jsonWriter.writeAny(fieldValue);
    }
};

ObjectWriterProvider objectWriterProvider = new ObjectWriterProvider();
objectWriterProvider.register(Season.class, seasonWriter);
JSONWriter.Context writeContext = JSONFactory.createWriteContext(objectWriterProvider);
String jsonString = JSON.toJSONString(student, writeContext);
System.out.println(jsonString);

打印结果:

{"favoriteSeason":"SUMMER","name":"tom","age":18}
{"favoriteSeason":"夏天","name":"tom","age":18}

Process finished with exit code 0

从结果中可以看到,enum 默认序列化时使用的是枚举常量,我们使用自定义序列化器指定序列化 Season 枚举类时使用它的 description 字段作为字段值。

还有更简单的方法,就是使用 @JSONField(value = true)注解设置枚举类要序列化时使用的字段,下面的 jsonField 注解的使用这个章节中讲了。

JSONField注解的使用

@Data
public class Student {
    @JSONField(ordinal = 2)
    private Integer age;
    private Season favoriteSeason;
    @JSONField(ordinal = 1)
    private String name;
    @JSONField(format = "yyyyMMdd")
    private Date birthday;
    @JSONField(serialize = false)
    private String address;
    @JSONField(deserialize = false)
    private String favoriteFood;
    @JSONField(name = "GENDER")
    private Gender gender;
}

@JSONField(ordinal = 2)注解设置了字段在序列化为 json 后的排列顺序,越小排在越前。
@JSONField(format = "yyyyMMdd")注解设置了在序列化 Date 类型的 birthday 字段时使用的日期格式。
@JSONField(serialize = false)注解设置了 address 字段不会被序列化,也就是序列化的结果中不会包含 address 字段。
@JSONField(deserialize = false)注解设置了将 json 反序列化成 student 对象时,不会反序列化 favoriteFood 字段,也就是 favoriteFood 字段会为 null
@JSONField(name = "GENDER")注解设置了 gender 字段序列化成 json 时的字段名为 GENDER。

如果类的字段是 public 并且有 get 和 set 方法,@JSONField(deserialize = false) 会失效。bean 类都尽量标准一点,属性都设置为 private,提供 get 和 set 方法,这样会减少异常的发生。

@Getter
public enum Season {
    SPRING("春天", "万物复苏"),
    SUMMER("夏天", "热"),
    AUTUMN("秋天", "秋高气爽"),
    WINTER("冬季", "冷");

    private final String description;

    @JSONField(value = true)
    private final String features;

    Season(String description, String features) {
        this.description = description;
        this.features = features;
    }
}

@JSONField(value = true)设置了 Season 枚举类序列化成 json 时会使用 features 字段做为其值,而不是默认使用的枚举常量。

通过Features配置序列化和反序列化的行为

https://alibaba.github.io/fastjson2/features_cn

在fastjson 2.x中,有两个Feature,分别用来配置序列化和反序列化的行为。

  • JSONWriter.Feature 配置序列化的行为
  • JSONReader.Feature 配置反序列化的行为
Student student = new Student();
student.setName("tom");
student.setAge(18);
// 输出对象中值为null的字段
System.out.println(JSON.toJSONString(student, JSONWriter.Feature.WriteNulls));

JSONPath 从 json 字符串中读取字段值

String str = "{\"address\":\"翻斗大街翻斗花园二号楼1001室\",\"favoriteFood\":\"炸小肉丸\",\"name\":\"图图\",\"age\":3,\"id\":10}";

JSONPath path = JSONPath.of("$.id");
JSONReader parser = JSONReader.of(str);
Integer result = (Integer) path.extract(parser);

System.out.println(result);

JSONPath 是一等公民。

本文作者:王陸

本文链接:https://www.cnblogs.com/wkfvawl/p/18709986

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   王陸  阅读(39)  评论(0编辑  收藏  举报
历史上的今天:
2022-02-11 Elasticsearch(二)进阶、优化、面试题
2022-02-11 SparkSQL
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起