我有以下用于 JodaTime 处理的序列化程序:
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);
}
}
然后,在每个模型对象上,我这样做:
@JsonSerialize(using=JodaDateTimeJsonSerializer.class )
public DateTime getEffectiveDate() {
return effectiveDate;
}
通过上述设置,@ResponseBody
和 Jackson Mapper 肯定可以工作。但是,我不喜欢我一直写 @JsonSerialize
的想法。我需要的是在模型对象上没有 @JsonSerialize
的解决方案。是否可以在 spring xml 中的某处编写此配置作为一个配置?
感谢您的帮助。
最佳答案
虽然您可以为每个日期字段添加注释,但最好为您的对象映射器进行全局配置。如果你使用 jackson ,你可以配置你的 Spring 如下:
<bean id="jacksonObjectMapper" class="com.company.CustomObjectMapper" />
<bean id="jacksonSerializationConfig" class="org.codehaus.jackson.map.SerializationConfig"
factory-bean="jacksonObjectMapper" factory-method="getSerializationConfig" >
</bean>
对于 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 可以使用您需要的任何格式。
关于json - Spring @ResponseBody Jackson JsonSerializer 与 JodaTime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10649356/