All the examples of @JsonSerialize and JsonSerializer implementations are similar to the following.
public class JodaDateTimeJsonSerializer extends JsonSerializer<DateTime> {
private static final String dateFormat = ("MM/dd/yyyy");
@Override
public void serialize(DateTime date, JsonGenerator gen, SerializerProvider provider)
throws IOException, JsonProcessingException {
String formattedDate = DateTimeFormat.forPattern(dateFormat).print(date);
gen.writeString(formattedDate);
}
}
It has a class-level variable that defines its runtime behaviour. This cannot be changed at runtime via configuration.
How can I make dateFormat
above a configurable property, while using @JsonSerialize(using = JodaDateTimeJsonSerializer.class)
on a property?
Right now, I'm considering just making it a static non-final property on the serializer implementation that is set at runtime by the application on run. Doesn't make for a very proper implementation. Edit: The ideal solution will allow me to ~inject~ (edit: pass in) only the required configuration into the serializer, not retrieve configuration from some global.
Note: I do not want to create a new data type for this property (they are all Strings) and I do not want to create a custom bean serializer (they can be annotated on any String property anywhere). Because of this, I also cannot use SimpleModule::addSerializer(class, serializer)
method as they should not be added to all String properties.