春季 MVC 中的杰克逊对象映射器不起作用 [英] Jackson Object Mapper in spring MVC not working

查看:36
本文介绍了春季 MVC 中的杰克逊对象映射器不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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,就像下面这样(从这个 教程,所以是 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)

这篇关于春季 MVC 中的杰克逊对象映射器不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆