FastJSON使用技巧几例。
字段名称映射
FastJSON 指定字段输出名称,例如类属性名是 name,希望JSON序列化的时候使用名称 userName怎么办?
- 使用 @JSONField 注解指定名称,对应Jackson中的 @JsonProperty("name")注解。
public class User {
@JSONField(name = "user_name")
private String name;
@JSONField(name = "user_age")
private int age;
@JSONField(name = "register_date")
public Date getRegisterDate() {
return registerDate;
}
}
- 使用 SimplePropertyPreFilter 动态修改字段名
SimplePropertyPreFilter filter = new SimplePropertyPreFilter();
filter.getIncludes().add("name");
filter.getRenames().put("name", "user_name");
String json = JSON.toJSONString(user, filter);
FastJSON 日期格式化
Java中,FastJSON用JSON.toJSONString(dto), 其中 dto.updateDate: Date,在JSON字符串中,变成了 整数,而不是 "yyyy-mm-dd hh:nn:ss" 的格式,
updateDate已经用 @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")指定了格式,但不起作用?
在 FastJSON 中,@JsonFormat 注解是 Jackson 的注解,FastJSON 并不支持它。FastJSON 有自己的日期处理方式,以下是几种解决方案:
- 使用 FastJSON 的 @JSONField 注解
import com.alibaba.fastjson.annotation.JSONField;
public class DTO {
@JSONField(format = "yyyy-MM-dd HH:mm:ss")
private Date updateDate;
}
// 设置全局日期格式
JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
// 序列化时使用
String jsonString = JSON.toJSONString(dto);
- 序列化时指定日期格式
String jsonString = JSON.toJSONStringWithDateFormat(dto, "yyyy-MM-dd HH:mm:ss");
- 使用 SerializerFeature
String jsonString = JSON.toJSONString(dto, SerializerFeature.WriteDateUseDateFormat);
使用 FastJSON 的全局时区设置:
// 设置全局默认时区(在应用启动时设置一次)
JSON.defaultTimeZone = TimeZone.getTimeZone("GMT+8");
FastJSON 忽略属性输出的方法
FastJSON JSON.toJSONString的时候,如何忽略某些属性不输出?
在 FastJSON 中,有几种方法可以在使用 JSON.toJSONString() 时忽略某些属性不输出:
- 使用 @JSONField(serialize = false) 注解
public class User {
private String name;
@JSONField(serialize = false)
private String password;
}
这样在序列化时,password 属性将被忽略。
- 使用 SimplePropertyPreFilter
User user = new User();
user.setName("张三");
user.setPassword("123456");
SimplePropertyPreFilter filter = new SimplePropertyPreFilter();
filter.getExcludes().add("password");
String jsonString = JSON.toJSONString(user, filter);
PropertyFilter filter = new PropertyFilter() {
@Override
public boolean apply(Object object, String name, Object value) {
return !"password".equals(name);
}
};
String jsonString = JSON.toJSONString(user, filter);
SerializeFilter[] filters = new SerializeFilter[2];
filters[0] = new SimplePropertyPreFilter().addExclude("password");
filters[1] = new NameFilter() {...};
String jsonString = JSON.toJSONString(user, filters);
// 忽略所有null值字段
JSON.DEFAULT_GENERATE_FEATURE |= SerializerFeature.SkipTransientField.getMask();
// 忽略transient字段
JSON.DEFAULT_GENERATE_FEATURE |= SerializerFeature.SkipTransientField.getMask();
选择哪种方法取决于你的具体需求,注解方式适合固定的属性排除,而过滤器方式则更加灵活,可以在运行时动态决定排除哪些属性。