[英]Jackson serialize field with different custom serializers
Is it possible to write n custom serializers for a particular field and then sometimes use serializer A and another time use serializer B? 是否可以为特定字段编写n个自定义序列化程序,然后有时使用序列化程序A而又一次使用序列化程序B? I have written custom serializers before but I have used them by annotation which is not possible in this case.
我以前写过自定义序列化程序,但是我通过注释使用了它们,在这种情况下是不可能的。 I would really like to avoid something like views since I had to write a getter for each serializer implementation then.
我真的想避免使用类似view的方法,因为那时我必须为每个序列化程序实现编写一个getter方法。
This is what I have: 这就是我所拥有的:
@JsonSerialize(using = MongoIdSerializer.class)
String id;
This is what I want: 这就是我要的:
@JsonSerialize(using = <SerializerDeclaredByPropertyFile>)
String id;
You could write a custom serializer that you use on the property. 您可以编写在属性上使用的自定义序列化程序。
@JsonSerialize(using = DelegatingSerializer.class)
String id;
The implementation would be something like that: 实现将是这样的:
public class DelegatingSerializer extends JsonSerializer<String>{
public void serialize(String value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
JsonSerializer<String> serializer = getSerializer();
serializer.serialize(value, jgen, provider);
}
private JsonSerializer<String> getSerializer() {
...
return someSerializerInstance;
}
}
In the getSerializer
method you would return an instance of the correct serializer. 在
getSerializer
方法中,您将返回正确的序列化器的实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.