1.@JsonIgnoreProperties
在类上注解哪些属性不用参与序列化和反序列化
@Data
@JsonIgnoreProperties(value = { "word" })
public class Person {
private String hello;
private String word;
}
2.@JsonIgnore
属性上忽略
@Data
public class Person {
private String hello;
@JsonIgnore
private String word;
}
3.@JsonFormat
格式化序列化后的字符串
@Data
public class Person{
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm",timezone = "GMT+8")
private Date time;
private String hello;
private String word;
}
4.@JsonSerialize
序列化的时候通过重写的方法,可以加在get方法上,也可以直接加在属性上
@Data
public class Person {
private String hello;
private String word;
@JsonSerialize(using = CustomDoubleSerialize.class)
private Double money;
}
public class CustomDoubleSerialize extends JsonSerializer<Double> {
private DecimalFormat df = new DecimalFormat("#.##");
@Override
public void serialize(Double value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
jgen.writeString(df.format(value));
}
}
5.@JsonDeserialize
反序列化的时候通过重写的方法,可以加在set方法上,也可以直接加在属性上
@Data
public class Person {
private String hello;
private String word;
@JsonDeserialize(using = CustomDateDeserialize.class)
private Date time;
}
public class CustomDateDeserialize extends JsonDeserializer<Date> {
private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
@Override
public Date deserialize(JsonParser jp, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
Date date = null;
try {
date = sdf.parse(jp.getText());
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
}
5.@JsonInclude
Include.Include.ALWAYS
默认
Include.NON_DEFAULT
属性为默认值不序列化
Include.NON_EMPTY
属性为 空(“”) 或者为 NULL 都不序列化
Include.NON_NULL
属性为NULL 不序列化
@Data
public class OrderProcessTime {
@JsonInclude(JsonInclude.Include.ALWAYS)
private Date plan;
}
6.@JsonProperty
用于表示Json序列化和反序列化时用到的名字,例如一些不符合编程规范的变量命名
@Data
public class Person {
private String hello;
private String word;
private Date time;
@JsonProperty(value = "DeliveryTime")
private Integer deliveryTime;
}