我想在Spring启动应用程序中序列化一些google guava Multimap。
public class SomeDTO {
@JsonProperty
Multimap<A, B> prop = HashMultimap.create();
}
如果不使用自定义的jackson序列化程序,我会得到一些像
这样的结果{
"prop ":
{
"empty": false
}
}
这是definitley不是我想要得到的。我想到了类似的东西:
{
"nodes": {
"key0": [
{
"prop0": 2,
"prop1": 4
},
{
"prop0": 5,
"prop1": 6
}
],
"key1": [
{
"prop0": 23,
"prop1": 0
}
]
}
}
添加
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-guava</artifactId>
<version>${jackson.version}</version>
</dependency>
pom.xml似乎还不够......但是,我只是从整个春天开始//关键的宇宙,所以我想我错过了一些明显的东西。
答案 0 :(得分:3)
我提出的解决方案只是将@Bean
添加到我的主@Configuration
:
import com.fasterxml.jackson.databind.Module;
import com.fasterxml.jackson.datatype.guava.GuavaModule;
// More-obvious imports missing
@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,ObjectMapper
Bean方法有一个缺点:每次使用这种方式创建ObjectMapper时,所有先前的配置都会被丢弃。
如果你想向jackson添加模块 - 而不是覆盖以前的配置,这种方法更好:
import com.fasterxml.jackson.databind.Module;
import com.fasterxml.jackson.datatype.guava.GuavaModule;
// More-obvious imports missing
@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();
}
}