aCarella aCarella - 1 year ago 48
JSON Question

How to get JSON response from controller to another controller in Spring

I have one controller in an app that returns JSON data, like so:

@RequestMapping(value = "/{number}", method = RequestMethod.GET)
public String number(
HttpServletRequest request,
HttpServletResponse response,
@PathVariable int number
) {
JSONObject dataObject = new JSONObject();
dataObject.put("firstName", "Sheelten");
dataObject.put("lastName", "Pestay");

JSONArray data = new JSONArray();

return data.toString();

I have another controller on a different app, that I want to receive the JSON data, like so:

value = "/data/test/",
method = RequestMethod.GET
public String testService(
HttpServletRequest request,
HttpServletResponse response,
Model model
) {
return response.toString();

I'm not really sure how I would go about receiving the JSON data into my testService controller method. I've tried googling and using the response object with no luck.

Anyone have an idea how I'd do this?

Answer Source

Found an answer, in case anyone else is ever looking for a solution to this.

If you are using Java with Spring, use the RestTemplate class. See below:

RestTemplate restTemplate = new RestTemplate();
String result = restTemplate.getForObject("http://yoururl/here", String.class);

The string result will be your JSON string.