Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I setup an object mapper with a module for Jackson and Spring

From this answer (https://stackoverflow.com/a/15605404/650784) I'm trying to setup Jackson to handle Joda datetimes in my DTOs, but I'm having difficulty understanding where the ObjectMapper code should live. I've read a bunch of different articles on the ObjectMapper, but they all seem to be dealing with older versions. I can take what I've found already and hack it to work, but I wanted to see what was was considered the correct way to do this with Spring 3.2.2/Jackson 2/Jersey. I should point out that I just want to add the joda time mapping module, I don't want any other customizations of jackson. I'm a bit of a spring newb, so forgive me if this is some simple and obvious answer I just missed.

like image 534
Zipper Avatar asked Jul 05 '13 19:07

Zipper


1 Answers

I never used Spring, but I had the same issue using RESTeasy framework. Knowing this, I'll try to give you some answers / direction to search.

To answer one of your questions, ObjectMapper "has to live" whenever you have to deal with a serialization / deserialization into / from json process. For example :

MyObject myObject = new MyObject();
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(myObject);

As pointed out in the link you provided, if you want to add a module to your ObjectMapper, you have to add the following line after creating your mapper :

mapper.registerModule(new AnyModuleYouNeed());

Now, I'm not a Spring user, but I assume you want this process to be automatic when spring provide its own serialization / deserialization process.

I found this on the web : http://magicmonster.com/kb/prg/java/spring/webmvc/jackson_custom.html

In your case, I think only point 2 and point 3 are usefull for you, and because you don't need to have a custom serializer, but you only need to add a module to your mapper, I think the custom ObjectMapper should look like that :

@Component
public class CustomObjectMapper extends ObjectMapper {
    public CustomObjectMapper() {
        registerModule(new AnyModuleYouNeed());
    }
}

In the web site I pointed to you, they speak alson about an elegant way to register a cusom ObjectMapper for Spring 3.1 users : http://magicmonster.com/kb/prg/java/spring/webmvc/mvc_spring_config_namespace.html

It may be usefull.

Finally, excuse my poor english, and let me know if you had your problem solved.

like image 186
PDauph Avatar answered Nov 03 '22 10:11

PDauph