Serialization of Java Money

Contents

The Spring frameworks helps with a lot of Java’s overhead configuration. Most of the time things just magically work. But sometimes not.

Spring uses Jackson for the serialization and deserialization of objects to and from json. It is very powerful and extendable. The serialized output can be placed as a value or payload in a Kafka message or used to send a response from an api. But here comes the problem. To be deserialized from a json string back to an object, the object itself must contain a parameterless constructor. And guess what, the java money class doesn’t have one.

A quick search will lead you to a repo from Zalando jackson-datatype-money. This package provides a fix for the problem.

All you need to do is:

Add the maven package to your pom file.

1
2
3
4
5
<dependency>
    <groupId>org.zalando</groupId>
    <artifactId>jackson-datatype-money</artifactId>
    <version>${jackson-datatype-money.version}</version>
</dependency>

With Spring Boot this is extremely simple. All ypu need is a Bean defined in a @Configuration and Jackson will automatically add the module.

1
2
3
4
5
6
7
8
@Configuration
class ServiceConfiguration {

    @Bean
    Module moneyModule() {
        return new MoneyModule();
    }
}

Using Sprung Boot makes development a lot easier. Most of the configuration is done but can be extended and overridden to match a special need.