[英]Create a type aware Jackson deserializer
我想配置一個傑克遜解串器,該函數根據被注釋字段的目標類型而有所不同。
public class Car {
@JsonSerialize(using=IdSerializer.class)
@JsonDeserialize(using=IdDeserializer.class)
String id
}
public class Bus {
@JsonSerialize(using=IdSerializer.class)
@JsonDeserialize(using=IdDeserializer.class)
Id id
}
Jackson序列化程序知道轉換數據的類型,因此可以正常工作:
public class IdSerializer extends JsonSerializer<Object> {
@Override
public void serialize(Object value, JsonGenerator jsonGen, SerializerProvider provider) throws IOException {
// value is the annotated field class
if(value instanceof String)
jsonGen.writeObject(...);
else if (value instanceof Id)
jsonGen.writeObject(...);
else
throw new IllegalArgumentException();
}
}
Jackson解串器似乎不知道將數據轉換成的目標類型:
public class IdDeserializer extends JsonDeserializer<Object> {
@Override
public Object deserialize(JsonParser jp, DeserializationContext context) throws IOException {
// what is the annotated field class?
}
}
在序列化程序中,您可以添加有關類型的額外信息,這將在反序列化期間為您提供幫助。
從您發布的IdSerializer建立...
public class IdSerializer extends JsonSerializer<Object> {
@Override
public void serialize(Object value, JsonGenerator jsonGen, SerializerProvider provider) throws IOException {
// value is the annotated field class
if(value instanceof String){
jsonGen.writeStartObject();
jsonGen.writeFieldName("id");
jsonGen.writeObject(value);
jsonGen.writeFieldName("type");
jsonGen.writeString("String");
jsonGen.writeEndObject();
}
else if (value instanceof Id){
Id id = (Id) value;
jsonGen.writeStartObject();
jsonGen.writeFieldName("id");
jsonGen.writeString(id.getStuff());
jsonGen.writeFieldName("type");
jsonGen.writeString("Id");
jsonGen.writeEndObject();
}
else{
throw new IllegalArgumentException();
}
}
}
在反序列化器中,您可以解析此“類型”字段並返回適當類型的Object。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.