Ananth Chelladurai
Ananth Chelladurai

Reputation: 110

How to make a REST call from Spring MVC Controller and return the response as it is

I am trying to make a webservice call from my Spring MVC controller using RestTemplate, I was wondering if there is a way to return the response as it is without unmarshaling to a Java object.

For example like in play framework,

HttpResponse res = WS.url(url).get(); renderJSON(res.getString()); // or res.getJson()

Most of my responses would be JSON or very rare case it might be a String.

Upvotes: 2

Views: 8316

Answers (1)

Santosh Joshi
Santosh Joshi

Reputation: 3320

Here's some code snippet;

## JAVA Code

@Autowired
RestOperations operations;

@RequestMapping(method = RequestMethod.GET)
    public String index( @PathVariable("id") String id, Model model) {

    //a) Call webservice using restemplate or using any other method
    //b) get the data from service
    //c) set data in modal

    String jsonFeed = operations.getForObject("URL", String.class);
    model.addAttribute("jsonFeed", jsonFeed);
}

## JSP CODE

// fetch the jsonFeed variable set in the modal attribute and set it into a java script variable and use the way u want.

<script type="text/javascript">
       var jsonObjToUse = jQuery.parseJSON(${jsonFeed})
 </script>

Upvotes: 3

Related Questions