Vishal Rathore
Vishal Rathore

Reputation: 137

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

Upvotes: 2

Views: 2159

Answers (2)

Rahul Kumar
Rahul Kumar

Reputation: 2831

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.

Upvotes: 0

Ulises
Ulises

Reputation: 9635

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:

Upvotes: 1

Related Questions