简体   繁体   中英

RESTful web services in java

I am trying to pass list of Long in my resource as post data and consume type is application/xml . I am also passing two path params. It is giving me exception "media type not supported".

Please help me to solve this. this is the code and I am having exception..

@POST
    @Path("/temp/{abc}")
    @Consumes(MediaType.APPLICATION_XML)
    @Produces(MediaType.APPLICATION_XML)
    public List<Long> createUser2(List<User> users,@PathParam("abc") String abc) {
//.................//
        List<Long> listLong=new ArrayList<Long>();
        listLong.add(1L);
        listLong.add(2L);
        System.out.println("temp called");
        return listLong;
    }




> org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException:
> MessageBodyWriter not found for media type=application/xml

The problem is that there's no conversion code that knows how to automatically change a Long or a List<Long> into XML. At the very least, information about what the name of the containing element must be present, and JAXB (the default supported mechanism) only applies that sort of thing at the level of a class.

The fix is to create a wrapper class with suitable JAXB annotations and return that. You might need to tweak the class to get exactly the serialization you want, but that's not hard.

@XmlRootElement(name = "userinfo")
public class UserInfo {
    @XmlElement
    public List<Long> values;
    // JAXB really requires a no-argument constructor...
    public UserInfo() {}
    // Convenience constructor to make the code cleaner...
    public UserInfo(List<Long> theList) {
        values = theList;
    }
}
@POST
@Path("/temp/{abc}")
@Consumes(MediaType.APPLICATION_XML)
@Produces(MediaType.APPLICATION_XML)
// NOTE THE CHANGE OF RESULT TYPE
public UserInfo createUser2(List<User> users,@PathParam("abc") String abc) {
    //.................//
    List<Long> listLong=new ArrayList<Long>();
    listLong.add(1L);
    listLong.add(2L);
    System.out.println("temp called");
    return new UserInfo(listLong); // <<<< THIS LINE CHANGED TOO
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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