Register a custom Jackson ObjectMapper using Spring Javaconfig

For a project for a client I’m working on, we are creating a JSON REST interface as a proxy for other systems. Our system collects data and transforms it to be used by the clients of our API. Most of the data we send are Strings, but for a new feature, we are migrating some of our code to Joda Money, a very convenient way of handling basic money operations.

To send our Money data back to our clients, we do a bit of conversion. For this, we use a Jackson Serializer, which looks a bit like this:

However, finding out how to register this class was a bit a hassle, and turned out to be trivial once we found out. To register the Serializer, you’ll need to have a custom ObjectMapper, like the following:

Then we need to register the ObjectMapper in the JavaConfig of our Spring application. This can be done with the following configuration:

And that’s it. Now Jackson is automatically configured to convert all Money objects to cents using the ObjectMapper. I hope this helps for people who need this in the future so that it might save some time!

5 replies
  1. Matthew
    Matthew says:

    It would be really nice to see the code for CustomSerializerFactory. Are you extending SerializerFactory, BasicSerializerFactory or BeanSerializerFactory and, if so, what are you overriding?

    • David
      David says:

      Prior to Jackson 2, CustomSerializerFactory was a part of Jackson, so he is just using the library provided class, not creating his own.

    • Erik Pragt
      Erik Pragt says:

      Hi Ben,

      It’s been a while, but I think you’re right, and the bean name must be exactly this name. Could you try and let me know if that works for you?

      • Ben
        Ben says:

        Hi Erik,
        Thanks for the swift response. I have the exact name that you have used, and it is still not being picked up. Do you remember if you had to add anything to the web.xml or anything like that?

        Thanks in advance.

Comments are closed.