简体   繁体   中英

How to return An arraylist in Rest Webservice

//Main service 

@Path("/test")
public class ReturnMultiple {

    public static ArrayList<String> al = new ArrayList<String>();

    @POST
    @Path("/new/{name}")
    @Produces(MediaType.TEXT_PLAIN)
    public ArrayList<String> display(@PathParam("name") String name) {
        al.clear();
        Todo td = new Todo();
        td.setName(name);
        al.add(td.getName());
        return al;
    }
}

// This is Pojo

public class Todo {

    private String name;

    public void setName(String name) {

        this.name = name;
    }

    public String getName() {
        return name;
    }

}

Whenever I hit the service I get this error as Below

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

You can't use ArrayList and produce TEXT_PLAIN. You'd have to use JSON. To setup JSON message body write in jax-rs you need to supply a @Provider for an ObjectMapper. Here's an example :

I guess, you need a mapper implementation which helps in the serialization and deserialization. Without that it doesn't know how to convert an arraylist into text/plain or application/json or for that matter any other MIME type.

if you are dealing with application/json, jackson library works as really good mapper. It has messagebodyreader and messagebodywriter for you to do the difficult job.

you might have a way to provide a mapper for your rest services (as a provider), in some implementation it picks itself if you use jackson jar which I remember while using resteasy.

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