Reputation: 6121
Is it possible to write n custom serializers for a particular field and then sometimes use serializer A and another time use serializer 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.
This is what I have:
@JsonSerialize(using = MongoIdSerializer.class)
String id;
This is what I want:
@JsonSerialize(using = <SerializerDeclaredByPropertyFile>)
String id;
Upvotes: 0
Views: 84
Reputation: 5185
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.
Upvotes: 2