问题描述
我有一个与 Spring boot 项目中的 Jackson 配置相关的问题
I have a question related to the Jackson configuration on my Spring boot project
我尝试自定义对象序列化.
I try to customize my Object serialization.
在我的配置中添加一个新的配置 bean 之后
After added a new config bean in my config
@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 中
When I try to output an instance of my class User the json result is not in 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 配置
Maybe I need to register something in my Jersey config to activate my custom obejctMapper Config
@Configuration
public class JerseyConfig extends ResourceConfig {
public JerseyConfig() {
packages("my.package);
}
}
谢谢
推荐答案
为 JAX-RS/Jersey 应用程序配置 ObjectMapper
的一般方法是使用 ContextResolver
.例如
The general way to configure the ObjectMapper
for JAX-RS/Jersey applications is use a ContextResolver
. For example
@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;
}
}
它应该通过包扫描被拾取,或者你可以明确注册它,如果它不在包范围内
It should be picked up with the package scan, or you can explicitly register it, if it's not within the package scope
public JerseyConfig() {
register(new ObjectMapperContextResolver());
// Or if there's is an injection required
// register it as a .class instead of instance
}
ContextResolver
在编组和解组期间被调用.被序列化或反序列化的类/类型将传递给 getContext
方法.因此,您甚至可以针对不同类型甚至更多用例使用多个映射器.
The ContextResolver
is called during the marshalling and unmarshalling. The class/type being serialzed or deserialized into will be passed to the getContext
method. So you could even use more than one mapper for different types, or even more use cases.
从 Spring Boot 1.4 开始,您只需创建一个 ObjectMapper
Spring bean,Spring Boot 将为您创建 ContextResolver
,并使用您的 ObjectMapper代码>
Starting from Spring Boot 1.4, you can just create an ObjectMapper
Spring bean, and Spring Boot will create the ContextResolver
for you, and use your ObjectMapper
// in your `@Configuration` file.
@Bean
public ObjectMapper mapper() {}
这篇关于春季靴子泽西杰克逊的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!