Natasha Natasha - 1 month ago 29
JSON Question

How to make java rest api return multiple json objects

I'm creating a REST Service in JAva, and below is the code part:

@GET
@Path("/getsummary")
@Produces("application/json")

public Response summary()
{

VoltDAOImpl voltDao = new VoltDAOImpl();
Map<String ,List<HashMap<String,String>>> returnList= voltDao.getOrderDetails("PEAKM" , "Hydra" ,
"" , voltDao.client,"notional" ,1000);
List<HashMap<String,String>> totalSlpSummaryList = returnList.get("total_slp_summary");
List<HashMap<String,String>> totalSlpSummaryBySideList = returnList.get("total_slp_summary_by_side");
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();

String json1 = null;
String json2 = null;
try {
json1 = ow.writeValueAsString(totalSlpSummaryList);
json2 = ow.writeValueAsString(totalSlpSummaryBySideList);
System.out.println(json1);
System.out.println(json2);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


return Response.status(200).entity(json1).build();
}


Right now, the above is only returning json1 object but I want it to return both json1 and json2. How do I achieve that?

Answer
String bothJson = "["+json1+","+json2+"]"; //Put both objects in an array of 2 elements
return Response.status(200).entity(bothJson).build();

or

String bothJson = "["+json1+","+json2+"]"; //Put both objects in an array of 2 elements
return Response.getWriter().write(bothJson);

or

String[] str = new String[2];
str[0] = json1;
str[1] = json2;
return Response.status(200).entity(str).build();

Try this, the concept is create a matrix/array and send it.

Comments