Return JSONArray instead of JSONObject, Jersey JAX-RS

后端 未结 2 629
情深已故
情深已故 2020-12-18 00:05

I am using Jersey to make some of my services RESTful.

My REST service call returns me

{\"param1\":\"value1\", \"param2\":\"value2\         


        
相关标签:
2条回答
  • 2020-12-18 00:56

    To return the entries in array-type style, you should build your entity from 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 face some trouble according to return type of toArray() method - you could explicitly cast your array:

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

    UPD: try to convert your list to JSONArray:

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

    and then:

    Response.ok(arr).build(); 
    
    0 讨论(0)
  • 2020-12-18 01:07

    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();
    }
    

    The 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:

    [{"fn":"1","ln":"2"}, {"fn":"3","ln":"4"}, {"fn":"5","ln":"6"}]
    
    0 讨论(0)
提交回复
热议问题