常用配置
#jackson
#日期格式化
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
#spring.jackson.date-format=yyyy-MM-dd
#格式化输出
spring.jackson.serialization.indent_output=true
#忽略无法转换的对象
spring.jackson.serialization.fail_on_empty_beans=false
#设置空如何序列化
spring.jackson.defaultPropertyInclusion=NON_EMPTY
#允许对象忽略json中不存在的属性
spring.jackson.deserialization.fail_on_unknown_properties=false
#允许出现特殊字符和转义符
spring.jackson.parser.allow_unquoted_control_chars=true
#允许出现单引号
spring.jackson.parser.allow_single_quotes=true
#设置空如何序列化
spring.jackson.defaultPropertyInclusion
JsonInclude.Include.ALWAYS 默认
JsonInclude.Include.NON_DEFAULT 属性为默认值不序列化
JsonInclude.Include.NON_EMPTY 属性为 空(””) 或者为 NULL 都不序列化
JsonInclude.Include.NON_NULL 属性为NULL 不序列化
jackson注解主要涉及到的jar包为jackson-annotations.jar,官方文档地址https://github.com/FasterXML/jackson-annotations/wiki/Jackson-Annotations
public class User {
@JsonProperty("user_name")
public String username;
public String password;
}
// 序列化为如下格式username变成了user_name
{"password":"123456","user_name":"zhangsan"}
@JsonIgnoreProperties({"username", "price"})
public class Pet {
private String username;
private String password;
private Date birthday;
private Double price;
}
// 指定序列化时忽略username、price字段
{"password":"123456","birthday":1533887811261}
public class Pet {
@JsonIgnore
private String username;
private String password;
private Date birthday;
private Double price;
}
// @JsonIgnore加在属性上面,使序列化时忽略该字段
{"password":"123456","birthday":1533888026016,"price":0.6}
public class Pet {
private String username;
private String password;
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone="GMT+8")
private Date birthday;
private Double price;
}
// @JsonFormat加在属性上面,用于jackson对时间格式规定,注意要指定中国时区为+8
{"username":"哈哈","password":"123456","birthday":"2018-08-10 16:17:51","price":0.6}
@JsonInclude(Include.NON_NULL)
public class Pet {
private String username;
private String password;
private Date birthday;
private Double price;
}
// @JsonInclude加在类上面,jackson序列化时会忽略无意义的字段,例如username和price是空值,那么就不序列化这两个字段
{"password":"123456","birthday":1533890045175}
1、用在字段上,
2、用在类上,那对这个类的全部属性起作用 ;
参数意义:
JsonInclude.Include.ALWAYS 默认
JsonInclude.Include.NON_DEFAULT 属性为默认值不序列化
JsonInclude.Include.NON_EMPTY 属性为 空(””) 或者为 NULL 都不序列化
JsonInclude.Include.NON_NULL 属性为NULL 不序列化
一般会使用自定义的序列化器,例如自定义MyJsonSerializer,用来处理Double类型序列化时保留两位小数,就非常好用
public class MyJsonSerializer extends JsonSerializer{
@Override
public void serialize(Double value, JsonGenerator gen, SerializerProvider serializers)
throws IOException, JsonProcessingException {
if (value != null)
gen.writeString(BigDecimal.valueOf(value).
setScale(2, BigDecimal.ROUND_HALF_UP).toString()); // ROUND_HALF_UP四舍五入
}
}
使用方式
public class Pet {
private String username;
private String password;
private Date birthday;
@JsonSerialize(using=MyJsonSerializer.class)
private Double price;
}
// 指定序列化price属性时使用自定义MyJsonSerializer,对Double类型进行自定义处理,保留两位小数
{"username":"哈哈","password":"123456","birthday":1533892290795,"price":"0.60"}