Return JSONArray instead of JSONObject, JAX-RS Jersey

I use Jersey to do some of my RESTful services.

My REST service call returns me

{"param1":"value1", "param2":"value2",...."paramN":"valueN"} 

But I want him to return

 ["param1":"value1", "param2":"value2",...."paramN":"valueN"] 

What changes do I need to make in the code below?

 @GET @Produces(MediaType.APPLICATION_JSON) public List<com.abc.def.rest.model.SimplePojo> getSomeList() { /* Do something */ return listOfPojos; } 

Part of my web.xml file is as follows

  <servlet> <servlet-name>Abc Jersey REST Service</servlet-name> <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class> <init-param> <param-name>com.sun.jersey.config.property.packages</param-name> <param-value>com.abc.def.rest</param-value> </init-param> <load-on-startup>0</load-on-startup> </servlet> 

Thanks!

+7
source share
2 answers

You can define your service method as follows using Person POJO:

 @GET @Produces("application/json") @Path("/list") public String getList(){ List<Person> persons = new ArrayList<>(); persons.add(new Person("1", "2")); persons.add(new Person("3", "4")); persons.add(new Person("5", "6")); // takes advantage to toString() implementation to format as [a, b, c] return persons.toString(); } 

POJO Class:

 @XmlRootElement public class Person { @XmlElement(name="fn") String fn; @XmlElement(name="ln") String ln; public Person(){ } public Person(String fn, String ln) { this.fn = fn; this.ln = ln; } @Override public String toString(){ try { // takes advantage of toString() implementation to format {"a":"b"} return new JSONObject().put("fn", fn).put("ln", ln).toString(); } catch (JSONException e) { return null; } } } 

The results will look like this:

 [{"fn":"1","ln":"2"}, {"fn":"3","ln":"4"}, {"fn":"5","ln":"6"}] 
+11
source

To return an array style entry, you must create your entity from an array. Try the following:

 @GET @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON}) public Response getSomeList() { List<com.abc.def.rest.model.SimplePojo> yourListInstance = new List<com.abc.def.rest.model.SimplePojo>(); /* Do something */ return Response.ok(yourListInstance.toArray()).build(); } 

if you encounter some problem in accordance with the type of the return type toArray() - you can explicitly specify your array:

 Response .ok((com.abc.def.rest.model.SimplePojo[])yourListInstance.toArray()) .build(); 

UPD: try converting your list to JSONArray:

 JSONArray arr = new JSONArray(); for (SimplePojo p : yourListInstance) { arr.add(p); } 

and then:

 Response.ok(arr).build(); 
+2
source

All Articles