简体   繁体   English

从Jersey资源返回超类

[英]Returning superclasses from Jersey resource

I'm doing a very simple thing that should just work, IMO. 我正在做一个很简单的事情,应该工作,IMO。 I've got a resource like: 我有类似的资源:

@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("{nodeType}/{uuid}")
public Object getResourceInfo(@PathParam("nodeType") String nodeType,
                              @PathParam("uuid") String uuid,
                              @Context SecurityContext authority) { ...

Note I'm returning type Object. 注意我将返回对象类型。 This is because depending on the call (here depending on the nodeType argument) I want to return a different concrete class (which will always be @XmlRootElement) and have that get marshalled out into the response. 这是因为根据调用(这里取决于nodeType参数),我想返回不同的具体类(始终为@XmlRootElement),并将其编组到响应中。

However, this does not work. 但是,这不起作用。 I get exception like: 我得到像这样的异常:

Exception Description: A descriptor for class com.mycompany.XmlElementTypeInstance was not found in the project.  For JAXB, if the JAXBContext was bootstrapped using TypeMappingInfo[] you must call a marshal method that accepts TypeMappingInfo as an input parameter.

If I change Object to a single subclass, it works. 如果我将Object更改为单个子类,则它可以工作。 But I want it to be able to handle any subclass, XmlElementTypeInstance, XmlElementTypeInstance2, etcetc. 但我希望它能够处理任何子类,XmlElementTypeInstance,XmlElementTypeInstance2等。

I tried making a common interface from which all of the XmlElementTypeInstance subclasses derive, but then I only get those properties in the interface, not the extra properties in the subclasses. 我尝试创建一个公共接口,所有XmlElementTypeInstance子类都从该接口派生,但是随后我仅在接口中获得那些属性,而不是子类中的其他属性。 Playing with @XmlElementRef and adding all possible properties to the common interface is extremely ugly and can't work quite correctly to generate the JSON I want, so please don't suggest that. 使用@XmlElementRef并将所有可能的属性添加到公共接口非常丑陋,并且无法正确生成我想要的JSON,因此请不要这样做。 =) =)

Is there any way to do this? 有什么办法吗? It seems like simple, basic, necessary functionality... any other REST framework I've used, no problem... 似乎简单,基本,必要的功能...我使用过的任何其他REST框架,都没问题...

The solution it turns out is simple (had to read the JSR instead of the actual Jersey docs, however!) 原来的解决方案很简单(但是,必须阅读JSR而不是实际的Jersey文档!)

Instead of returning Object, returning Response (section 3.3.3 of JSR 339) with the object set as the entity forces the implementation to pick an appropriate MessageBody{Writer,Reader} at runtime. 返回而不是返回Object,而是将对象设置为实体,返回Response(JSR 339的3.3.3节),以强制实现在运行时选择适当的MessageBody {Writer,Reader}。

return Response.ok().entity(<the object>).build();

Lost way too much time on this. 在这方面浪费了太多时间。 Hope it helps someone later. 希望以后能对某人有所帮助。 =/ = /

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM