@JsonProperty
用于表示Json序列化和反序列化时用到的名字,例如一些不符合编程规范的变量命名
public class Person {
@JsonProperty("delivery_time")
private Integer deliveryTime;
}
@JsonAlias
这个注解只在反序列化时起作用,指定该java属性可以接受的更多名称
public class Person {
@JsonAlias("delivery_time", "DeliveryTime")
private Integer deliveryTime;
}
@JsonInclude
Include.Include.ALWAYS
默认
Include.NON_DEFAULT
属性为默认值不序列化,比如int类型为0,boolean类型为false等
Include.NON_EMPTY
属性为空("")或者为NULL都不序列化
Include.NON_NULL
属性为NULL不序列化
@Data
public class OrderProcessTime {
@JsonInclude(JsonInclude.Include.ALWAYS)
private Date plan;
}
@JsonRawValue
用于表示Json序列化和反序列化时用到的名字,例如一些不符合编程规范的变量命名,如果字段正好是一个json的string,那这个注解可以将这个string直接转成Json对象
public class Person {
@JsonRawValue
private String jsonString;
}
@JsonIgnore
在属性上标注哪些属性不参与序列化和反序列化
public class Person {
private String name;
@JsonIgnore
private String age;
}
@JsonIgnoreProperties
在类上标注哪些属性不参与序列化和反序列化
@JsonIgnoreProperties("age", ignoreUnknown=true)
public class Person {
private String name;
private String age;
}
@JsonFormat
格式化序列化后的字符串
public class Person{
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm",timezone = "GMT+8")
private Date time;
}
@JsonSerialize
序列化的时候通过重写的方法,可以加在get方法上,也可以直接加在属性上
public class Person {
@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));
}
}
@JsonDeserialize
反序列化的时候通过重写的方法,可以加在set方法上,也可以直接加在属性上
@Data
public class Person {
@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;
}
}
@JsonTypeInfo
jackson多态处理
@JsonTypeInfo:定义子类类型标识
use:使用的标识类型,CLASS、MINIMAL_CLASS使用类名匹配,NAME使用自定义名称匹配,CUSTOM可实现TypeIdResolverBase进行个性化解析。
include:定义类型标识的包含形式,常用EXISTING_PROPERTY标识pojo内的属性。
property:定义属性名称。
visible:序列化时标识字段是否可见。
defaultImpl:匹配失败时用的兜底子类。
@JsonSubTypes:标识和具体子类的对应关系
@Data
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
property = "type",
visible = true
)
@JsonSubTypes({
@JsonSubTypes.Type(value = InputPageModel.class, name = "input"),
@JsonSubTypes.Type(value = NumberPageModel.class, name = "number")
})
public abstract class Page {
private String type;
private String name;
private String uiType;
private String label;
}
@Data
public class InputPage extends Page {
private String input;
}
@Data
public class NumberPage extends Page {
private Integer number;
}