How to return An arraylist in Rest Webservice

Question
//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


Show source
| java   | rest   2017-01-07 07:01 2 Answers

Answers ( 2 )

  1. 2017-01-07 08:01

    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:

  2. 2017-01-07 09:01

    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.

◀ Go back