前言
想要将出参VO对象的属性 private Boolean auditResult; 转换为 通过 / 不通过 ,返回给前端。
springboot有入参的类型转换器,那么理应有出参转换器才对
于是从 @JsonFormat 找到了 com.fasterxml.jackson.annotation
进而翻阅了如下链接
jackson-annotations overview
jackson-docs - 截止20210312最新版本是2.12
下面对常用的几个做一下笔记记录,方便以后查阅
- 1、修改属性key值
@JsonProperty("重命名的属性值")
- 2、修改value值 / value值转换
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
public class AuditResultSerializer extends JsonSerializer<Boolean> {
@Override
public void serialize(Boolean b, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
jsonGenerator.writeString(b == true ? "通过" : "不通过");
}
}
/** 审批是否通过:true 通过 false 不通过 */
@JsonSerialize(using = AuditResultSerializer.class)
private Boolean passed;
- 3、忽略属性值
public class Value {
public int value;
@JsonIgnore public int internalValue;
}
@JsonIgnoreProperties({ "extra", "uselessValue" })
public class Value {
public int value;
}
@JsonIgnoreProperties(ignoreUnknown=true)
public class PojoWithAny {
public int value;
}
- 4、反序列化为具体的子类对象
@JsonTypeInfo(use=Id.MINIMAL_CLASS, include=As.PROPERTY, property="type") // Include Java class simple-name as JSON property "type"
@JsonSubTypes({@Type(Car.class), @Type(Aeroplane.class)}) // Required for deserialization only
public abstract class Vehicle {
}
public class Car extends Vehicle {
public String licensePlate;
}
public class Aeroplane extends Vehicle {
public int wingSpan;
}
public class PojoWithTypedObjects {
public List<Vehicle> items;
}
JSON 示例:
{ "items": [
{ "type": "Car", "licensePlate": "X12345" },
{ "type": "Aeroplane", "wingSpan": 13 }
]}