Jackson对象映射器在春季MVC无法正常工作 [英] Jackson Object Mapper in spring MVC not working
问题描述
每个具有Date格式的对象都被序列化为long。
Every object with Date format is being serialized as a long.
我读过我需要创建一个自定义对象映射器
I've read around that I need to create a custom object mapper
所以我做了:
public class CustomObjectMapper extends ObjectMapper {
public CustomObjectMapper() {
super();
configure(Feature.WRITE_DATES_AS_TIMESTAMPS, false);
setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
}
}
我是还将自定义映射器注册为转换器
I've also registered that custom mapper as a converter
@Override
protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(converter());
addDefaultHttpMessageConverters(converters);
}
@Bean
MappingJacksonHttpMessageConverter converter() {
MappingJacksonHttpMessageConverter converter = new MappingJacksonHttpMessageConverter();
converter.setObjectMapper(new CustomObjectMapper());
return converter;
}
但是,它仍然不起作用,我接受了很长一段时间约会。
but still, it doesn't work, and I recieve a long as a date.
知道我做错了什么吗?
推荐答案
你需要实现自己的Dateserializer,就像下面这样(从这个教程<获得它) / a>,所以道具给Loiane,而不是我;-)):
You'll need to implement your own Dateserializer, just like the following (got it from this tutorial, so props to Loiane, not me ;-) ):
package ....util.json;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.SerializerProvider;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
@Component
public class JsonDateSerializer extends JsonSerializer<Date>{
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm "); // change according to your needs
@Override
public void serialize(Date date, JsonGenerator gen, SerializerProvider provider)
throws IOException {
String formattedDate = dateFormat.format(date);
gen.writeString(formattedDate);
}
}
然后你可以添加以下内容日期对象的注释,它将保持正常:
then you could just add the following annotation to your Date-Objects and it will persist fine:
@JsonSerialize(using = JsonDateSerializer.class)
public Date getCreated() {
return created;
}
至少它适用于Spring 3.2.4和jackson 1.9.13。
At least it works with spring 3.2.4 and jackson 1.9.13 here.
编辑:考虑使用 FastDateFormat
代替 SimpleDateFormat
,因为它是线程安全替代方案(如Loianes文章的评论中所述)
edit: Think about using FastDateFormat
instead of SimpleDateFormat
, for it's the threadsafe-alternative (as mentioned in the comments of Loianes article)
这篇关于Jackson对象映射器在春季MVC无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!