Marshalling of generic types in Jersey

限于喜欢 提交于 2019-12-05 14:15:48
ndtreviv

After battling with this myself I discovered the answer is fairly simple. In your service, return a built response of a GenericEntity (http://docs.oracle.com/javaee/6/api/javax/ws/rs/core/GenericEntity.html) typed accordingly. For example:

@GET
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public Response findAll(){
    return Response.ok(new GenericEntity<TestEntity>(facade.findAllWithCount()){}).build();
}

See this post as to why you cannot simply return GenericEntity: Jersey GenericEntity Not Working

A more complex solution could be to return the GenericEntity directly and create your own XmlAdapter (http://jaxb.java.net/nonav/2.2.4/docs/api/javax/xml/bind/annotation/adapters/XmlAdapter.html) to handle marshalling/unmarshalling. I've not tried this, though, so it's just a theory.

I solved it using @XmlSeeAlso annotation:

@XmlSeeAlso(TestEntity.class)
@XmlRootElement
public class QueryResult<T> implements Serializable {
    ...
}

Another possibility is to use @XmlElementRefs.

hage

I had exactly the same issue. The problem occurs because of Java's type erasure.

My first approach was to generate a result class for each entity type:

public class Entity1Result extends QueryResult<Entity1> { ... }

public class Entity2Result extends QueryResult<Entity2> { ... }

I returned the generic QueryResult<> in my serivces only for built-in types like QueryResult<String>, or QueryResult<Integer>

But this was cumbersome, because I had a lot of entities. So my other approach was to use only JSON and I changed my result class to be non-generic and use an Object result field:

public class QueryResult {
   private Object result;
}

It works fine, Jersey is able to serialize everything I give it into JSON (Note: I don't know if it is important, but the QueryResult and all my entities still have @Xml... annotations. This works also for lists with own entity types.

If you have problems with collections, you can also see this question

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!