我有一个非常简单的休息网络服务,返回一系列问题。当返回的问题数大于零时,此代码按预期工作。但是如果服务器返回一个像[]那样的空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);
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;
}
}
客户代码:
public List<Question> getQuestionsByGroupId(int id) {
return digiRest.path("/questions/byGroupId/" + id).get(new GenericType<List<Question>>() {});
}
问题类只是一个简单的pojo。
答案 0 :(得分:0)
我知道这不是你问题的答案,但我选择在球衣上使用GSON,用于我目前的项目。 (我尽可能地避免使用JAXB),我发现它非常容易和有弹性。
你只需申报
@Consumes(MediaType.TEXT_PLAIN)
或
@Produces(MediaType.TEXT_PLAIN)
或两者,并使用GSON marshaller / unmarshaller,并使用简单的字符串。非常容易调试,也可以单元测试......
答案 1 :(得分:0)
使用Jackson可能有所帮助。 请参阅org.codehaus.jackson.map.ObjectMapper和org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion.NON_EMPTY
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.annotate.JsonSerialize;
public class SampleContextResolver implements ContextResolver<ObjectMapper>
{
@Override
public ObjectMapper getContext(Class<?> type)
{
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationConfig(mapper.getSerializationConfig()
.withSerializationInclusion(JsonSerialize.Inclusion.NON_EMPTY)
}
}