我需要返回几个结果和结果总数的客户列表。我必须在具有不同实体的几个地方执行此操作,因此我想要一个具有这两个属性的通用类:
@XmlRootElement
public class QueryResult<T> implements Serializable {
private int count;
private List<T> result;
public QueryResult() {
}
public void setCount(int count) {
this.count = count;
}
public void setResult(List<T> result) {
this.result = result;
}
public int getCount() {
return count;
}
public List<T> getResult() {
return result;
}
}
Run Code Online (Sandbox Code Playgroud)
和服务:
@GET
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public QueryResult<TestEntity> findAll(
QueryResult<TestEntity> findAll = facade.findAllWithCount();
return findAll;
}
Run Code Online (Sandbox Code Playgroud)
实体不重要:
@XmlRootElement
public class TestEntity implements Serializable {
...
}
Run Code Online (Sandbox Code Playgroud)
但这会导致: javax.xml.bind.JAXBException: class test.TestEntity nor any of its super class is known to this context.
仅返回集合很容易,但我不知道如何返回我自己的泛型类型。我尝试使用GenericType但没有成功 - 我认为这是收藏品。
在自己与这个斗争之后,我发现答案很简单。在您的服务中,返回相应类型的 GenericEntity ( http://docs.oracle.com/javaee/6/api/javax/ws/rs/core/GenericEntity.html )的构建响应。例如:
@GET
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public Response findAll(){
return Response.ok(new GenericEntity<TestEntity>(facade.findAllWithCount()){}).build();
}
Run Code Online (Sandbox Code Playgroud)
请参阅这篇文章,了解为什么您不能简单地返回 GenericEntity:Jersey GenericEntity Not Working
更复杂的解决方案可能是直接返回 GenericEntity 并创建您自己的 XmlAdapter ( http://jaxb.java.net/nonav/2.2.4/docs/api/javax/xml/bind/annotation/adapters/XmlAdapter.html ) 处理编组/解组。不过,我还没有尝试过,所以这只是一个理论。
我使用@XmlSeeAlso注释解决了它:
@XmlSeeAlso(TestEntity.class)
@XmlRootElement
public class QueryResult<T> implements Serializable {
...
}
Run Code Online (Sandbox Code Playgroud)
另一种可能性是使用@XmlElementRefs.