我有一个非常简单的休息Web服务返回一个问题列表.当返回的问题数大于零时,此代码按预期工作.但是如果服务器返回一个像[]那样的空json数组,JAXB会创建一个包含一个问题实例的列表,其中所有字段都设置为null!
我是Jersey和JAXB的新手,所以我不知道我是否没有正确配置它或者这是否是一个已知问题.有小费吗?
客户端配置:
DefaultApacheHttpClientConfig config = new DefaultApacheHttpClientConfig();
config.getProperties().put(DefaultApacheHttpClientConfig.PROPERTY_HANDLE_COOKIES, true);
config.getClasses().add(JAXBContextResolver.class);
//config.getClasses().add(JacksonJsonProvider.class); // <- Jackson causes other problems
client = ApacheHttpClient.create(config);
Run Code Online (Sandbox Code Playgroud)
JAXBContextResolver:
@Provider
public final class JAXBContextResolver implements ContextResolver<JAXBContext> {
private final JAXBContext context;
private final Set<Class> types;
private final Class[] cTypes = { Question.class };
public JAXBContextResolver() throws Exception {
this.types = new HashSet(Arrays.asList(cTypes));
this.context = new JSONJAXBContext(JSONConfiguration.natural().build(), cTypes);
}
@Override
public JAXBContext getContext(Class<?> objectType) {
return (types.contains(objectType)) ? context : null;
}
}
Run Code Online (Sandbox Code Playgroud)
客户代码:
public List<Question> getQuestionsByGroupId(int id) {
return digiRest.path("/questions/byGroupId/" + id).get(new GenericType<List<Question>>() {});
}
Run Code Online (Sandbox Code Playgroud)
问题类只是一个简单的pojo.
我知道这并不完全是您问题的答案,但对于我当前的项目,我选择在球衣之上使用 GSON。(我尝试尽可能避免 JAXB),并且我发现它非常简单且有弹性。
你只需要声明
@Consumes(MediaType.TEXT_PLAIN)
Run Code Online (Sandbox Code Playgroud)
或者
@Produces(MediaType.TEXT_PLAIN)
Run Code Online (Sandbox Code Playgroud)
或两者兼而有之,并使用 GSON 编组器/解组器,并使用纯字符串。非常容易调试,单元测试也......
| 归档时间: |
|
| 查看次数: |
2574 次 |
| 最近记录: |