Spring 3.2 和 Jackson 2:添加自定义对象映射器 [英] Spring 3.2 and Jackson 2: add custom object mapper

查看:48
本文介绍了Spring 3.2 和 Jackson 2:添加自定义对象映射器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 Spring MVC 中开发 REST web 服务.我需要更改 jackson 2 序列化 mongodb objectids 的方式.我不确定该怎么做,因为我找到了 jackson 2 的部分文档,我所做的是创建一个自定义序列化程序:

I'm developing a REST webservice in spring MVC. I need to change how jackson 2 serialize mongodb objectids. I'm not sure of what to do because I found partial documentation for jackson 2, what I did is to create a custom serializer:

public class ObjectIdSerializer extends JsonSerializer<ObjectId> {


    @Override
    public void serialize(ObjectId value, JsonGenerator jsonGen,
            SerializerProvider provider) throws IOException,
            JsonProcessingException {
        jsonGen.writeString(value.toString());
    }
}

创建一个对象映射器

public class CustomObjectMapper extends ObjectMapper {

    public CustomObjectMapper() {
        SimpleModule module = new SimpleModule("ObjectIdmodule");
        module.addSerializer(ObjectId.class, new ObjectIdSerializer());
        this.registerModule(module);
    }

}

然后注册映射器

<mvc:annotation-driven>
    <mvc:message-converters register-defaults="true">
        <bean
            class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
            <property name="objectMapper">
                <bean class="my.package.CustomObjectMapper"></bean>
            </property>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

我的 CustomConverter 从未被调用.我认为 CustomObjectMapper 的定义是错误的,我从 jackson 1.x 的一些代码中改编了它

My CustomConverter is never called. I think the CustomObjectMapper definition is wrong,I adapted it from some code for jackson 1.x

在我的控制器中,我使用@ResponseBody.我哪里做错了?谢谢

In my controllers I'm using @ResponseBody. Where am I doing wrong? Thanks

推荐答案

你应该用 @JsonSerialize 注释.在您的情况下,它可能是:

You should annotate corresponding model field with @JsonSerialize annontation. In your case it may be:

public class MyMongoModel{
   @JsonSerialize(using=ObjectIdSerializer.class)
   private ObjectId id;
}

但在我看来,最好不要将实体模型用作 VO.更好的方法是拥有不同的模型并在它们之间进行映射.您可以在此处找到我的示例项目(我以 Spring 3 和 Jackson 2 为例使用日期序列化).

But in my opinion, it should better don't use entity models as VOs. Better way is to have different models and map between them. You can find my example project here (I used date serialization with Spring 3 and Jackson 2 as example).

这篇关于Spring 3.2 和 Jackson 2:添加自定义对象映射器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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