Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
622 views
in Technique[技术] by (71.8m points)

web services - Spring, Jackson and Customization (e.g. CustomDeserializer)

Being still a little unfamiliar with Spring, I have encountered a problem that makes it necessary implementing my a custom deserialzer for Jackson. The procedure is described in a small tutorial, however, I am stuck with Spring. I do not understand, where

 ObjectMapper mapper = new ObjectMapper();

in Spring MVC is carried out when json is deserializes by a method of a controller class. So I do not know, what to do in order to replace the default deserializer by a custom deserialiser.

Any suggestions most welcome.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You don't say how you're using Jackson in Spring, so I'll assume you're using it through <mvc:annotation-driven/> and the @RequestBody and/or @ResponseBody annotations.

One of the things that <mvc:annotation-driven/> does is to register a AnnotationMethodHandlerAdapter bean which comes with a number of pre-configured HttpMessageConverter beans, including MappingJacksonHttpMessageConverter, which handles marshalling to and from Jackson-annotated model classes.

Now MappingJacksonHttpMessageConverter has a setObjectMapper() method, which allows you to override the default ObjectMapper. But since MappingJacksonHttpMessageConverter is created behind the scenes by <mvc:annotation-driven/>, you can't get to it.

However, <mvc:annotation-driven/> is just a convenient short-cut. It's just as a valid to declare your own AnnotationMethodHandlerAdapter bean, injecting into it your own MappingJacksonHttpMessageConverter bean (via the messageConverters property), and injecting your own customized ObjectMapper into that.

You then have the problem of how to build a custom ObjectMapper, since it's not a very Spring-friendly class. I suggest writing your own simple implementation of FactoryBean.

So you'd end up with something like this:

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
   <property name="messageConverters">
      <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
         <property name="objectMapper">
            <bean class="com.x.MyObjectMapperFactoryBean"/>
         </property>
      </bean>
   </property>
</bean>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.7k users

...