A message body writer for Java class java.util.ArrayList…and MIME media type text/xml was not found

后端 未结 4 958
孤独总比滥情好
孤独总比滥情好 2020-11-28 11:11

Im using Jersey to build a REST Service and want to return a Collection as XML.

@GET
@Produces(MediaType.TEXT_XML)
@Path(\"/direct         


        
4条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-28 11:57

    The only thing that worked for me so far is to create my own Wrapper object.

    Don't forget the @XmlRootElement annotation to explain JAXB how to parse it.

    Note that this will work for any type of object - in this example I used ArrayList of String.

    e.g.

    The Wrapper object should look like this:

    import java.util.ArrayList;
    import javax.xml.bind.annotation.XmlRootElement;
    
    @XmlRootElement
    public class ArrayListWrapper {
        public ArrayList myArray = new ArrayList();
    }
    

    And the REST method should look like this:

    @GET
    @Produces(MediaType.TEXT_XML)
    @Path("/directgroups")
    public ArrayListWrapper getDirectGroupsForUser(@PathParam("userId") String userId) {
        try {
            ArrayListWrapper w = new ArrayListWrapper();
            w.myArray = service.getDirectGroupsForUser(userId, null, true);
            return w;
        } catch (UserServiceException e) {
            LOGGER.error(e);
            throw new RuntimeException(e.getMessage());
        }
    }
    

提交回复
热议问题