从 Jersey 资源返回超类
Returning superclasses from Jersey resource
IMO,我正在做一件非常简单的事情,应该可以正常工作。我有这样的资源:
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("{nodeType}/{uuid}")
public Object getResourceInfo(@PathParam("nodeType") String nodeType,
@PathParam("uuid") String uuid,
@Context SecurityContext authority) { ...
请注意,我正在 returning 类型对象。这是因为根据调用(这里取决于 nodeType 参数),我想 return 一个不同的具体 class(它将始终是 @XmlRootElement)并将其编组到响应中。
但是,这不起作用。我得到这样的异常:
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.
如果我将对象更改为单个子class,它就可以工作。但我希望它能够处理任何 subclass、XmlElementTypeInstance、XmlElementTypeInstance2 等。
我尝试创建一个通用接口,所有 XmlElementTypeInstance 子 classes 都从该接口派生,但后来我只在接口中获得这些属性,而不是子 classes 中的额外属性.使用@XmlElementRef 并将所有可能的属性添加到公共接口是非常丑陋的,并且不能完全正确地生成我想要的 JSON,所以请不要建议。 =)
有什么办法吗?看起来很简单、基本、必要的功能……我用过的任何其他 REST 框架都没有问题……
事实证明解决方案很简单(但是必须阅读 JSR 而不是实际的 Jersey 文档!)
不是返回对象,而是返回将对象设置为实体的响应(JSR 339 的第 3.3.3 节)强制实现在运行时选择适当的 MessageBody{Writer,Reader}。
return Response.ok().entity(<the object>).build();
为此浪费了太多时间。希望它能帮助以后的人。 =/
IMO,我正在做一件非常简单的事情,应该可以正常工作。我有这样的资源:
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("{nodeType}/{uuid}")
public Object getResourceInfo(@PathParam("nodeType") String nodeType,
@PathParam("uuid") String uuid,
@Context SecurityContext authority) { ...
请注意,我正在 returning 类型对象。这是因为根据调用(这里取决于 nodeType 参数),我想 return 一个不同的具体 class(它将始终是 @XmlRootElement)并将其编组到响应中。
但是,这不起作用。我得到这样的异常:
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.
如果我将对象更改为单个子class,它就可以工作。但我希望它能够处理任何 subclass、XmlElementTypeInstance、XmlElementTypeInstance2 等。
我尝试创建一个通用接口,所有 XmlElementTypeInstance 子 classes 都从该接口派生,但后来我只在接口中获得这些属性,而不是子 classes 中的额外属性.使用@XmlElementRef 并将所有可能的属性添加到公共接口是非常丑陋的,并且不能完全正确地生成我想要的 JSON,所以请不要建议。 =)
有什么办法吗?看起来很简单、基本、必要的功能……我用过的任何其他 REST 框架都没有问题……
事实证明解决方案很简单(但是必须阅读 JSR 而不是实际的 Jersey 文档!)
不是返回对象,而是返回将对象设置为实体的响应(JSR 339 的第 3.3.3 节)强制实现在运行时选择适当的 MessageBody{Writer,Reader}。
return Response.ok().entity(<the object>).build();
为此浪费了太多时间。希望它能帮助以后的人。 =/