在jaxrs中获取javax.xml.bind.UnmarshalException

时间:2013-01-07 09:56:47

标签: java rest jax-rs

在为xml提供多个元素标记时,我收到了javax.xml.bind.UnmarshalException。我的JAXB注释类与下面的类相似。

@XmlRootElement
    public class Group {

        private String id;
        private String name;

        @XmlElementWrapper(name="groups")
        @XmlElement(name="group")
        private ArrayList<Group> grouplist;

        public void setGrouplist(ArrayList<Group> grouplist){
            this.grouplist=grouplist;
        }

        public ArrayList<Group> getGrouplist(){
            return grouplist;
        }
           ---------------------------
           ---------------------------
           -------------------------

输入xml将是这样....

<groups>
<group>
<id>1</id>
<name>asd</name>
<designation>SE</designation>
</group>
</groups>

我的资源是这样的。

    @POST
    @Consumes(MediaType.APPLICATION_XML)
    @Produces(MediaType.APPLICATION_XML)    
 public Response addGroup(@Context HttpServletRequest req)throws JAXBException,IOException{
 JAXBContext jaxb = JAXBContext.newInstance(Group.class);
 Group grps= (Group)jaxb.createUnmarshaller().unmarshal(req.getInputStream());

当我从req中提供上述xml时,我得到以下异常

    com.sun.jersey.spi.container.ContainerResponse mapMappableContainerException
SEVERE: The exception contained within MappableContainerException could not be mapped to a response, re-throwing to the HTTP container
javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"groups"). Expected elements are <{}group>: unexpected element (uri:"", local:"groups"). Expected elements are <{}group>

当我通过删除groups标签和相应的@xmlelementWrapper arraylist在xml中给出一个组时,上面的工作正常。

2 个答案:

答案 0 :(得分:1)

我认为你在课堂上缺少一个根元素。将其更改为:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement
public class Group {
...
...

答案 1 :(得分:0)

如果您在使用Apache CXF的JAX-RS 2.0客户端时遇到此问题,可能会遇到CXF-5980