Spring @ResponseBody Jackson JsonSerializer with JodaTime
jackson, jodatime, json, spring, spring-mvc
Solution
Although you can put an annotation for each date field, is better to do a global configuration for your object mapper. If you use jackson you can configure your spring as follow:
<bean id="jacksonObjectMapper" class="com.company.CustomObjectMapper" />
<bean id="jacksonSerializationConfig" class="org.codehaus.jackson.map.SerializationConfig"
factory-bean="jacksonObjectMapper" factory-method="getSerializationConfig" >
</bean>
For CustomObjectMapper:
public class CustomObjectMapper extends ObjectMapper {
public CustomObjectMapper() {
super();
configure(Feature.WRITE_DATES_AS_TIMESTAMPS, false);
setDateFormat(new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss 'GMT'ZZZ (z)"));
}
}
Of course, SimpleDateFormat can use any format you need.
Problem
I have below Serializer for JodaTime handling: ``` 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); } } ``` Then, on each model objects, I do this: ``` @JsonSerialize(using=JodaDateTimeJsonSerializer.class ) public DateTime getEffectiveDate() { return effectiveDate; } ``` With above settings, `@ResponseBody` and Jackson Mapper sure works. However, I don't like the idea where I keep writing `@JsonSerialize`. What I need is a solution without the `@JsonSerialize` on model objects. Is it possible to write this configuration somewhere in spring xml as a one configuration? Appreciate your help.