fastjson使用
文章目录
一、简介
fastjson是阿里推出的json序列化反序列化工具,拥有良好的性能。这里对常用操作进行介绍。
二、准备
2.1 github地址
https://github.com/alibaba/fastjson
2.2 官网文档地址
https://github.com/alibaba/fastjson/wiki/Quick-Start-CN
参考:https://www.w3cschool.cn/fastjson/
2.3 maven依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.57</version>
</dependency>
三、使用
创建示例类School和Stu,创建自定序列化类AddressSerialize,及对象初始化。
@Data
//@JSONType(serialzeFeatures = SerializerFeature.BeanToArray, parseFeatures = Feature.SupportArrayToBean)
static class School{
public String schoolNo;
public String schoolName;
public Date createTime;
}
@Data
static class Stu {
public Integer id = 1;
//重定义转为json串后的字段名
@JSONField(name = "stu_no")
public String stuNo;
//serialize是否序列化,deserialize是否反序列化
@JSONField(serialize = false, deserialize = false)
public String stuName;
public String stuNickName;
//format格式化时间,ordinal指定字段顺序
@JSONField(name = "create_time", format = "yyyy-MM-dd HH:mm:ss", ordinal = 2)
public Date createTime;
public Date updateTime;
//自定义字段序列化方式
@JSONField(serializeUsing = AddressSerialize.class)
public String address;
public School school;
public List<School> schoolList;
}
//自定义序列化类
public static class AddressSerialize implements ObjectSerializer {
@Override
public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
serializer.write("地址:" + Objects.toString(object));
}
}
//示例准备
public static void main(String[] args) throws Exception {
Stu stu = new Stu();
stu.setId(1);
stu.setStuNo("001");
stu.setStuName("apple1");
stu.setAddress("china");
stu.setCreateTime(new Date());
stu.setUpdateTime(new Date());
School school = new School();
school.setSchoolNo("sc001");
school.setSchoolName("oraange1");
school.setCreateTime(new Date());
stu.setSchool(school);
stu.setSchoolList(Lists.newArrayList(school));
JSONObject obj= null;
String jsonStr = "";
}
3.1 常规使用
//序列化对象
jsonStr = JSON.toJSONString(school);
//反序列化
school = JSON.parseObject(jsonStr, School.class);
3.2 SerializerFeature使用
com.alibaba.fastjson.serializer.SerializerFeature类在序列化时可重构属性值(这里列举部分,更多操作请查看源码),示例如下:
//时间格式化,JSON.toJSONStringWithDateFormat,如 2019-05-08
jsonStr = JSON.toJSONStringWithDateFormat(stu, "yyyy-MM-dd");
//时间格式化, 如 2019-05-08 22:10:01
jsonStr = JSON.toJSONString(stu, SerializerFeature.WriteDateUseDateFormat);
//时间格式化,如 2019-05-08T22:08:14.541+08:00
jsonStr = JSON.toJSONString(stu, SerializerFeature.UseISO8601DateFormat);
//取消循环引用,否则有相同对象时会出现类似$ref字符
jsonStr = JSON.toJSONString(stu, SerializerFeature.DisableCircularReferenceDetect);
//序列化为数组(不含key),结果为:[1557758507085,"oraange1","sc001"]
jsonStr = JSON.toJSONString(school, SerializerFeature.BeanToArray);
//反序列化
school = JSON.parseObject(jsonStr, School.class, Feature.SupportArrayToBean);
3.3 过滤器使用
对象转json时,可以对key、value、属性等进行过滤(修改或忽略操作),示例如下:
//key过滤器
NameFilter nameFilter = (Object object, String name, Object value) -> CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, name);
jsonStr = JSON.toJSONString(stu, nameFilter);
//value过滤器
ValueFilter valueFilter = (Object object, String name, Object value) -> "##"+value+"##";
jsonStr = JSON.toJSONString(stu, valueFilter);
//属性过滤器,基于属性判断是否序列化
PropertyFilter propertyFilter = (Object object, String name, Object value) -> name.toLowerCase().contains("time");
jsonStr = JSON.toJSONString(stu, propertyFilter);
3.4 注解使用
注解com.alibaba.fastjson.annotation.JSONField可对属性进行修改,示例如下:
//serialize是否序列化,deserialize是否反序列化
@JSONField(serialize = false, deserialize = false)
public String stuName;
//name重定义key,format格式化时间,ordinal指定字段顺序
@JSONField(name = "create_time", format = "yyyy-MM-dd HH:mm:ss", ordinal = 2)
public Date createTime;
//自定义字段序列化方式
@JSONField(serializeUsing = AddressSerialize.class)
public String address;
//注解在类上,对象序列化为不含key的数组
@JSONType(serialzeFeatures = SerializerFeature.BeanToArray, parseFeatures = Feature.SupportArrayToBean)
static class School{}
3.5 json文件读写使用
fastjson中的json文件读取,可用于大对象或大数组中,示例如下:
String jsonFilePath = "t.json";
//序列化
JSONWriter writer = new JSONWriter(new FileWriter(jsonFilePath));
writer.writeObject(school);
writer.close();
//反序列化
JSONReader reader = new JSONReader(new FileReader(jsonFilePath));
school = reader.readObject(School.class);
reader.close();
//大数组序列化
writer = new JSONWriter(new FileWriter(jsonFilePath));
writer.startArray();
writer.writeObject(school);
writer.endArray();
writer.close();
//大数组反序列化
reader = new JSONReader(new FileReader(jsonFilePath));
reader.startArray();
while(reader.hasNext()){
school = reader.readObject(School.class);
}
reader.endArray();
reader.close();
//大对象序列化
writer = new JSONWriter(new FileWriter(jsonFilePath));
writer.startObject();
writer.writeKey("schoolNo");
writer.writeValue("hehe");
writer.endObject();
writer.close();
//大对象反序列化
reader = new JSONReader(new FileReader(jsonFilePath));
reader.startObject();
while(reader.hasNext()){
String key = reader.readString();
String val = reader.readString();
}
reader.endObject();
reader.close();
3.6 排序问题
fastjson在序列化和反序列化时,默认会重排序(内部嵌套集合对象也会重排序)的。但现实使用中却常常需要按原始插入顺序。修改为原始插入规则如下:
- 创建JSONObject对象时,构造函数传True则不重排序。
- 反序列化时,JSON.parseObject()中传Feature.OrderedField则不重排序
示例如下:
//创建JSONObject对象
// obj = new JSONObject(); //重排序,结果:{"a":1,"b":2,"c":3,"d":4}
obj = new JSONObject(true); //按原始插入顺序存,结果:{"b":2,"a":1,"d":4,"c":3}
obj.put("b",2);
obj.put("a",1);
obj.put("d",4);
obj.put("c",3);
//反序列化
jsonStr = "{\"b\":2,\"a\":1,\"d\":4,\"c\":3}";
obj = JSON.parseObject(jsonStr);//重排序,结果为 {"a":1,"b":2,"c":3,"d":4}
obj = JSON.parseObject(jsonStr,Feature.OrderedField); //原始顺序 {"b":2,"a":1,"d":4,"c":3}
四、结尾
这里仅列出fastjson中的部分使用,更多操作请查看官方文档或源码。
本文介绍了阿里巴巴的fastjson,一个高性能的JSON库。内容包括fastjson的简介、如何在 Maven 中添加依赖,以及常规使用、SerializerFeature 序列化特性、过滤器、注解和排序问题的详细使用示例。

1544

被折叠的 条评论
为什么被折叠?



