FastJSON指南

用于将Java Bean序列化为JSON字符串 , 也可以从JSON字符串反序列化到 。
简单使用
com.alibabafastjson1.2.49
package com.ivan.json.entity;import java.util.Date;import com.alibaba.fastjson.annotation.JSONField;public class User {private Longid;private String name;@JSONField(format = "yyyy-MM-dd HH:mm:ss")private DatecreateTime;public Long getId() {return id;}public void setId(Long id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Date getCreateTime() {return createTime;}public void setCreateTime(Date createTime) {this.createTime = createTime;}}
package com.ivan.json;import java.util.Date;import com.alibaba.fastjson.JSON;import com.ivan.json.entity.User;public class SimpleTest {public static void main(String[] args) {serialize();deserialize();}public static void serialize() {User user = new User();user.setId(11L);user.setName("西安");user.setCreateTime(new Date());String jsonString = JSON.toJSONString(user);System.out.println(jsonString);}public static void deserialize() {String jsonString = "{\"createTime\":\"2018-08-17 14:38:38\",\"id\":11,\"name\":\"西安\"}";User user = JSON.parseObject(jsonString, User.class);System.out.println(user.getName());System.out.println(user.getCreateTime());}}
特性的使用
通过对生成的json格式的数据进行一些定制 , 比如可以输入的格式更好看 , 使用单引号而非双引号等 。例子程序如下:
package com.ivan.json;import java.util.Date;import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.serializer.SerializerFeature;import com.ivan.json.entity.User;public class SerializerFeatureTest {public static void main(String[] args) {User user = new User();user.setId(11L);user.setCreateTime(new Date());String jsonString = JSON.toJSONString(user, SerializerFeature.PrettyFormat, SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.UseSingleQuotes);System.out.println(jsonString);}}
输出的结果如下:
使用的输出结果
常用属性
名称含义
输出key时是否使用双引号,默认为true
使用单引号而不是双引号,默认为false
是否输出值为null的字段,默认为false
ng
Enum输出name()或者,默认为false
Date使用格式输出 , 默认为false
List字段如果为null,输出为[],而非null
ty
字符类型字段如果为null,输出为”“,而非null
o
数值字段如果为null,输出为0,而非null
lse
字段如果为null,输出为false,而非null
如果是true , 类中的Get方法对应的Field是 , 序列化时将会被忽略 。默认为true
按字段名称排序后输出 。默认为false
把\t做转义输出 , 默认为false不推荐设为true
结果是否格式化,默认为false
序列化时写入类型信息 , 默认为false 。反序列化是需用到
消除对同一对象循环引用的问题 , 默认为false
对斜杠’/’进行转义
将中文都会序列化为\uXXXX格式 , 字节数会多一些 , 但是能兼容IE 6 , 默认为false
at
全局修改日期格式,默认为false 。
har
一个对象的字符串属性中如果有特殊字符如双引号 , 将会在转成json时带有反斜杠转移符 。如果不需要转义 , 可以使用这个属性 。默认为false
将对象转为array输出
与注解的使用
提供了对序列化与反序列化进行定制 , 比如可以指定字段的名称 , 序列化的顺序 。用于属性 , 方法方法参数上 。的源码如下: