Jersey JSON 从骆驼大小写切换到下划线(蛇形大小写)
Jersey JSON switching from camel case to underscores (snake case)
我最近换了球衣 2,。
我浏览了 documentation/web 并了解了如何使用 .readEntity(ClassName.class);
将响应 class 转换为自定义 class
但我坚持使用 CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES
命名策略。
当前转换失败,因为响应字段带有“_”并且我的 POJO 有 Snake case 。
如有任何帮助,我们将不胜感激。
在 jersey1 中,我一直在这样做:
MyResponse myResponse = client
.resource(url)
.type(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
.post(RequestClass.class, request);
同样我无法实现 post 球衣 2:
当我在上面的代码中出现编译时错误:
我也试过了:
MyResponse myResponse = client
.target(getUrl())
.request()
.post(Entity.entity(request, MediaType.APPLICATION_JSON))
.readEntity(MyResponse.class);
但它没有创建 myResponse
对象,因为我得到的响应有 Snake_case 响应,但我的 POJO 有驼峰式字段。
这是 Jackson ObjectMapper
需要配置的东西。您可以在 ContextResolver
中执行此操作。基本上,你需要像
这样的东西
@Provider
public class MapperProvider implements ContextResolver<ObjectMapper> {
final ObjectMapper mapper;
public MapperProvider() {
mapper = new ObjectMapper();
mapper.setPropertyNamingStrategy(
PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
}
@Override
public ObjectMapper getContext(Class<?> cls) {
return mapper;
}
}
然后向您的客户注册
client.register(MapperProvider.class);
如果您在服务器上也需要此支持,那么您也需要在服务器上注册它。
我最近换了球衣 2,。
我浏览了 documentation/web 并了解了如何使用 .readEntity(ClassName.class);
但我坚持使用 CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES
命名策略。
当前转换失败,因为响应字段带有“_”并且我的 POJO 有 Snake case 。
如有任何帮助,我们将不胜感激。
在 jersey1 中,我一直在这样做:
MyResponse myResponse = client
.resource(url)
.type(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
.post(RequestClass.class, request);
同样我无法实现 post 球衣 2: 当我在上面的代码中出现编译时错误:
我也试过了:
MyResponse myResponse = client
.target(getUrl())
.request()
.post(Entity.entity(request, MediaType.APPLICATION_JSON))
.readEntity(MyResponse.class);
但它没有创建 myResponse
对象,因为我得到的响应有 Snake_case 响应,但我的 POJO 有驼峰式字段。
这是 Jackson ObjectMapper
需要配置的东西。您可以在 ContextResolver
中执行此操作。基本上,你需要像
@Provider
public class MapperProvider implements ContextResolver<ObjectMapper> {
final ObjectMapper mapper;
public MapperProvider() {
mapper = new ObjectMapper();
mapper.setPropertyNamingStrategy(
PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
}
@Override
public ObjectMapper getContext(Class<?> cls) {
return mapper;
}
}
然后向您的客户注册
client.register(MapperProvider.class);
如果您在服务器上也需要此支持,那么您也需要在服务器上注册它。