Sve*_*ges 5 spring json jackson
我在 Spring 3 MVC 应用程序中使用 Jackson JSON。为了不序列化每个日期字段,我创建了一个使用特定日期格式的自定义对象映射器:
@Component("jacksonObjectMapper")
public class CustomObjectMapper extends ObjectMapper
{
Logger log = Logger.getLogger(CustomObjectMapper.class);
@PostConstruct
public void afterProps()
{
log.info("PostConstruct... RUNNING");
//ISO 8601
getSerializationConfig().setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SZ"));
}
//constructors...
}
Run Code Online (Sandbox Code Playgroud)
这个自定义的 ObjectMapper 被注入到 JsonConverter 中:
<bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="supportedMediaTypes" value="application/json" />
<property name="objectMapper" ref="jacksonObjectMapper" /> <!-- defined in CustomObjectMapper -->
</bean>
Run Code Online (Sandbox Code Playgroud)
日志和序列化工作没有例外,但它没有选择日期格式,它简单地序列化为时间戳。@PostConstruct注解起作用了,方法中的日志语句在日志中。
有谁知道为什么会失败?
您可能还需要指定您想要文本日期序列化,方法是:
configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false);
Run Code Online (Sandbox Code Playgroud)
(虽然我假设设置非空日期格式也可能会触发它,但也许不会)
此外,您可以直接从构造函数配置映射器(这是安全的)。并不是说它应该改变行为,而是消除对单独配置方法的需要。
| 归档时间: |
|
| 查看次数: |
32246 次 |
| 最近记录: |