我编写了一个RESTful资源方法,它生成application/json
和application/xml
,它在类级别定义,下面是我的方法:
@GET
@Path("testing/getNames")
public Map<Long, String> getNames(@QueryParam("list") List<Long> list) {
// return invoking ejb method and return map
}
当我用json产生命中这个资源时,它会给出响应但是对于format = format.xml我得到以下异常:
Caused by: javax.xml.bind.MarshalException
- with linked exception:
[com.sun.istack.SAXException2: unable to marshal type "java.util.HashMap" as an element because it is missing an @XmlRootElement annotation]
at com.sun.xml.bind.v2.runtime.MarshallerImpl.write(MarshallerImpl.java:326)
at com.sun.xml.bind.v2.runtime.MarshallerImpl.marshal(MarshallerImpl.java:251)
at javax.xml.bind.helpers.AbstractMarshallerImpl.marshal(AbstractMarshallerImpl.java:110)
at org.glassfish.jersey.jaxb.internal.AbstractRootElementJaxbProvider.writeTo(AbstractRootElementJaxbProvider.java:190)
at org.glassfish.jersey.jaxb.internal.AbstractRootElementJaxbProvider.writeTo(AbstractRootElementJaxbProvider.java:169)
... 81 more
Caused by: com.sun.istack.SAXException2: unable to marshal type "java.util.HashMap" as an element because it is missing an @XmlRootElement annotation
at com.sun.xml.bind.v2.runtime.XMLSerializer.reportError(XMLSerializer.java:249)
at com.sun.xml.bind.v2.runtime.ClassBeanInfoImpl.serializeRoot(ClassBeanInfoImpl.java:338)
at com.sun.xml.bind.v2.runtime.property.ArrayReferenceNodeProperty.serializeListBody(ArrayReferenceNodeProperty.java:118)
at com.sun.xml.bind.v2.runtime.property.ArrayERProperty.serializeBody(ArrayERProperty.java:159)
at com.sun.xml.bind.v2.runtime.ClassBeanInfoImpl.serializeBody(ClassBeanInfoImpl.java:360)
at com.sun.xml.bind.v2.runtime.XMLSerializer.childAsSoleContent(XMLSerializer.java:593)
at com.sun.xml.bind.v2.runtime.ClassBeanInfoImpl.serializeRoot(ClassBeanInfoImpl.java:341)
at com.sun.xml.bind.v2.runtime.XMLSerializer.childAsRoot(XMLSerializer.java:494)
at com.sun.xml.bind.v2.runtime.MarshallerImpl.write(MarshallerImpl.java:323)
对此有何建议?
答案 0 :(得分:0)
添加了MapWrapper类
@XmlRootElement(name="MapWrapper")
public class MapWrapper implements Serializable{
private static final long serialVersionUID = 1L;
private Map<Long, String> yourMap;
public Map<Long, String> getYourMap() {
return yourMap;
}
public void setYourMap(Map<Long, String> yourMap) {
this.yourMap= yourMap;
}
}
并在资源方法中使用
@GET
@Path("testing/getNames")
public MapWrapper getNames(@QueryParam("list") List<Long> list) {
// return invoking ejb method and return map
}
答案 1 :(得分:-1)
您可以尝试将Map放入包装器
@XmlRootElement
public class MapWrapper {
Map<Long, String> yourMap;
}