Spring @ResponseBody Jackson JsonSerializer 与 JodaTime [英] Spring @ResponseBody Jackson JsonSerializer with JodaTime
问题描述
我有以下用于 JodaTime 处理的序列化程序:
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;
}
通过上述设置,@ResponseBody
和 Jackson Mapper 肯定可以工作.但是,我不喜欢我一直在编写 @JsonSerialize
的想法.我需要的是在模型对象上没有 @JsonSerialize
的解决方案.是否可以将这个配置写在 spring xml 中的某处作为一个配置?
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?
感谢您的帮助.
推荐答案
虽然您可以为每个日期字段添加注释,但最好为您的对象映射器进行全局配置.如果您使用 jackson,您可以按如下方式配置您的弹簧:
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>
对于 CustomObjectMapper:
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)"));
}
}
当然,SimpleDateFormat 可以使用您需要的任何格式.
Of course, SimpleDateFormat can use any format you need.
这篇关于Spring @ResponseBody Jackson JsonSerializer 与 JodaTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!