The Time
The Time

Reputation: 737

send JSON response with two method's return values

I have this method to consume JSON string I am getting here two return values.The first from the insertData method and it is integer 201 or 208 and the second value from getStopRoute it is ArrayList. How can I return the both value in Jersey with JSON in this case?

@Path("/data")
public class Receiver {



    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    public Response storeData(Data data) {

        String macD = data.getMac();
        int routeD = data.getRoute();
        double latD = data.getLatitude();
        double longD = data.getLongitude();

        Database db = new Database();
        int status = db.insertData(macD, routeD, latD, longD); // return 201 or 208
        ArrayList<Integer>  route_number = db.getStopRoute(latD, longD); //return [1,9,3]

        return Response.status(status).build();

    }

}

JSON Dependency:

<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-json-jackson</artifactId>
    <version>2.16</version>
</dependency>

Upvotes: 0

Views: 289

Answers (1)

jeorfevre
jeorfevre

Reputation: 2316

please consider doing so :

1. code

     @POST
        @Consumes(MediaType.APPLICATION_JSON)
        public Response storeData(Data data) {

            String macD = data.getMac();
            int routeD = data.getRoute();
            double latD = data.getLatitude();
            double longD = data.getLongitude();

            Database db = new Database();



           //inserted by jean
        SDBean bean= new SDBean();
        bean.status = db.insertData(macD, routeD, latD, longD);
        bean.routes= db.getStopRoute(latD, longD); //return [1,9,3]

        return Response.status(bean.status).entity(bean.toJson()).build();

    }

    //inserted by jean
    public class SDBean{

          public int status;
        //@Expose 
        public ArrayList<Integer> routes;
        public String toJson(){
             //if you use jackson


    ObjectMapper mapper = new ObjectMapper(); 
    String json =null;
    try {
        json = mapper.writeValueAsString(this);
    } catch (JsonProcessingException e) {

        e.printStackTrace();
    }
      return json;

        }

Enjoy :)

Upvotes: 1

Related Questions