春季靴泽西杰克逊 [英] Spring boot Jersey Jackson
问题描述
我在Spring启动项目中有一个与Jackson配置有关的问题
I have a question related to the Jackson configuration on my Spring boot project
As described on spring boot blog
我尝试自定义对象序列化.
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
的一般方法是使用
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() {}
这篇关于春季靴泽西杰克逊的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!