helt helt - 6 months ago 143
JSON Question

Enable json serialization of Multimap in Spring Boot Project

I want to serialize some google guava Multimap in a spring boot application.

public class SomeDTO {
@JsonProperty
Multimap<A, B> prop = HashMultimap.create();
}


Without using a customized jackson serializer, I get some result like

{
   "prop ":
   {
       "empty": false
   }
}


Which is definitley not what I seek to get. I thought of something like:

{
"nodes": {
"key0": [
{
"prop0": 2,
"prop1": 4
},
{
"prop0": 5,
"prop1": 6
}
],
"key1": [
{
"prop0": 23,
"prop1": 0
}
]
}
}


Adding

<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-guava</artifactId>
<version>${jackson.version}</version>
</dependency>


to the pom.xml seems not sufficient... However, I'm just starting with this whole spring // pivotal universe, so I guess I miss something obvious.

Answer

The solution i came up with is simply adding a @Bean to my main @Configuration:

@Configuration
@EnableAutoConfiguration
@ComponentScan
public class Application extends SpringBootServletInitializer {

    public static void main(final String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Override
    protected final SpringApplicationBuilder configure(final SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }

    @Bean
    ObjectMapper customizeJacksonConfiguration() {
        ObjectMapper om = new ObjectMapper();
        om.registerModule(new GuavaModule());
        return om;
    }
}

Afaik, the ObjectMapper Bean approach has one drawback: Everytime an ObjectMapper is created this way, all previous configuration gets thrown away.

If you want to add a module to jackson - instead of overriding previous configuration, this approach is better:

@Configuration
@EnableAutoConfiguration
@ComponentScan
public class Application extends SpringBootServletInitializer {

    public static void main(final String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Override
    protected final SpringApplicationBuilder configure(final SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }

    @Bean
    public Module guavaModule() {
        return new GuavaModule();
    }
}