小编典典

Spring靴泽西杰克逊

spring-boot

我在Spring启动项目中有一个与Jackson配置有关的问题

Spring Boot博客中所述

我尝试自定义对象序列化。

在我的配置中添加新的配置bean之后

@Bean
public Jackson2ObjectMapperBuilder jacksonBuilder() {
    Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();

    builder.propertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
    return builder;
}

当我尝试输出类User的实例时,json结果不在CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES中

Class User {
    private String firstName = "Joe Blow";

    public String getFirstName() {
        return firstName;
    }
}

json输出为:

{
  "firstName": "Joe Blow"
}

并不是

{
  "first_name": "Joe Blow"
}

也许我需要在Jersey配置中注册一些东西才能激活我的自定义obejctMapper配置

@Configuration
public class JerseyConfig extends ResourceConfig {
    public JerseyConfig() {
        packages("my.package);
    }
}

谢谢


阅读 331

收藏
2020-05-30

共1个答案

小编典典

ObjectMapper为JAX-RS /
Jersey应用程序配置的一般方法是使用ContextResolver。例如

@Provider
public class ObjectMapperContextResolver implements ContextResolver<ObjectMapper> {

    private final ObjectMapper mapper;

    public ObjectMapperContextResolver() {
        mapper = new ObjectMapper();
        mapper.setPropertyNamingStrategy(
            PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES
        );
    }

    @Override
    public ObjectMapper getContext(Class<?> type) {
        return mapper;
    }
}

应该在程序包扫描中将其提取,或者如果它不在程序包范围内,则可以显式注册它

public JerseyConfig() {
    register(new ObjectMapperContextResolver());
    // Or if there's is an injection required
    // register it as a .class instead of instance
}

ContextResolver打包和解包时被调用。序列化或反序列化的类/类型将传递给getContext方法。因此,您甚至可以将多个映射器用于不同类型,甚至更多用例。


更新

从Spring Boot 1.4开始,您可以只创建一个ObjectMapperSpring bean,然后Spring
Boot将为ContextResolver您创建,并使用您的ObjectMapper

// in your `@Configuration` file.
@Bean
public ObjectMapper mapper() {}
2020-05-30