在泽西岛编组通用类型
我需要返回几个结果和结果总数的客户列表。 我必须在具有不同实体的几个地方这样做,所以我希望有一个具有这两个属性的generics类:
@XmlRootElement public class QueryResult implements Serializable { private int count; private List result; public QueryResult() { } public void setCount(int count) { this.count = count; } public void setResult(List result) { this.result = result; } public int getCount() { return count; } public List getResult() { return result; } }
和服务:
@GET @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) public QueryResult findAll( QueryResult findAll = facade.findAllWithCount(); return findAll; }
实体并不重要:
@XmlRootElement public class TestEntity implements Serializable { ... }
但这会导致: javax.xml.bind.JAXBException: class test.TestEntity nor any of its super class is known to this context.
返回刚收集很容易,但我不知道如何返回我自己的generics类型。 我尝试使用GenericType
但没有成功 – 我认为它是collections品。
在与我自己斗争后,我发现答案很简单。 在您的服务中,返回相应键入的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(facade.findAllWithCount()){}).build(); }
看到这篇文章,为什么你不能简单地返回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 implements Serializable { ... }
另一种可能性是使用@XmlElementRefs
。
我有完全相同的问题。 出现问题的原因是Java的类型擦除。
我的第一种方法是为每个实体类型生成一个结果类:
public class Entity1Result extends QueryResult { ... } public class Entity2Result extends QueryResult { ... }
我在我的服务中返回了通用的QueryResult<>
,仅用于内置类型,如QueryResult
或QueryResult
但这很麻烦,因为我有很多实体。 所以我的另一种方法是只使用JSON,我将结果类更改为非generics并使用Object
结果字段:
public class QueryResult { private Object result; }
它运行正常,Jersey可以将我提供的所有内容序列化为JSON(注意:我不知道它是否重要,但是QueryResult
和我的所有实体仍然有@Xml...
注释。这也适用于列表自己的实体类型。
如果您对集合有疑问,也可以看到这个问题