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