Spring 3.2和Jackson 2:添加自定义对象映射器
我正在Spring MVC中开发一个REST Web服务。 我需要改变jackson2序列化mongodb objectids的方式。 我不知道该怎么办,因为我找到了jackson 2的部分文档,我做的是创建一个自定义序列化器:
public class ObjectIdSerializer extends JsonSerializer { @Override public void serialize(ObjectId value, JsonGenerator jsonGen, SerializerProvider provider) throws IOException, JsonProcessingException { jsonGen.writeString(value.toString()); } }
创建一个ObjectMapper
public class CustomObjectMapper extends ObjectMapper { public CustomObjectMapper() { SimpleModule module = new SimpleModule("ObjectIdmodule"); module.addSerializer(ObjectId.class, new ObjectIdSerializer()); this.registerModule(module); } }
然后注册映射器
我的CustomConverter永远不会被调用。 我认为CustomObjectMapper定义是错误的,我从jackson 1.x的一些代码改编它
在我的控制器中,我正在使用@ResponseBody。 我哪里做错了? 谢谢
您应该使用@JsonSerialize annontation注释相应的模型字段。 在你的情况下,它可能是:
public class MyMongoModel{ @JsonSerialize(using=ObjectIdSerializer.class) private ObjectId id; }
但在我看来,最好不要将实体模型用作VO。 更好的方法是在它们之间建立不同的模型和映射。 你可以在这里找到我的示例项目 (我使用Spring 3和Jackson 2作为示例的日期序列化)。
我该怎么做是:
创建注释以声明自定义序列化程序:
@Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface MyMessageConverter{ }
在mvcconfiguration文件中为此设置组件扫描
并创建一个实现HttpMessageConverter
。
@MyMessageConverter public MyConverter implements HttpMessageConverter{ //do everything that's required for conversion. }
创建一个extends AnnotationMethodHandlerAdapter implements InitializingBean
的类extends AnnotationMethodHandlerAdapter implements InitializingBean
。
public MyAnnotationHandler extends AnnotationMethodHandlerAdapter implements InitializingBean{ //Do the stuffs you need to configure the converters //Scan for your beans that have your specific annotation //get the list of already registered message converters //I think the list may be immutable. So, create a new list, including all of the currently configured message converters and add your own. //Then, set the list back into the "setMessageConverters" method. }
我相信这是你的目标所需要的一切。
干杯。
无需创建对象映射器。 将jackson-core-2.0.0.jar和jackson-annotations-2.0.0.jar添加到您的项目中。
现在,在处理服务时,将以下代码行添加到控制器:
@RequestMapping(value = "students", method = RequestMethod.POST, headers = "Accept=application/json", consumes = "application/json") public HashMap postStudentForm( @RequestBody Student student, HttpServletResponse response)
不要错过任何注释。