I try to return a list of Strings in Jersey as JSON and XML. I thought this would be trivial.
My first try was to write something like this
@GET
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Path("/bar")
public List<String> get() {
return dao.get();
}
and I expected an output similiar to this: ["string1", ..., "stringN] unfortunately I got this:
com.sun.jersey.api.MessageException: A message body writer for Java class java.util.LinkedList, and Java type java.util.List<java.lang.String>, and MIME media type application/json was not found
Then I wrote a wrapper StringList for List
@XmlRootElement
public class StringList {
private List<String> data;
public StringList() {
}
public StringList(List<String> data) {
this.data = data;
}
public List<String> getData() {
return data;
}
public void setData(List<String> data) {
this.data = data;
}
}
and modified the facade to
@GET
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Path("/foo")
public StringList stringlist() {
return new StringList(sl());
}
Which works great for Lists with more items than 1.
{"data":["foo","bar"]}
Unfortunately I get two unexepected results for one or zero elements
{"data": "just one"} // for one element i would expect {"data": ["just one"]}
null // for no elements i would expect {"data": []}
Am I doing something completly wrong? How can I fix this?