I am using get api for getting data from url but it give response in string format i want exact response or json response
`
@RestController
public class HelloController {
@GetMapping("/discover")
private String getApi(){
String url ="https://discover.search.hereapi.com/v1/discover?at=18.49093,73.8332&limit=2&q=restaurant&in=countryCode:IND&apiKey=hhV0nHGeHgrg5LACzw7dDJNe49bYCNvkCWxV94LlHno";
RestTemplate restTemplate = new RestTemplate();
String result = restTemplate.getForObject(url,String.class);
//Object[] result = restTemplate.getForObject(url, Object[].class);
//List<String> arr = new ArrayList<String>();
//arr.add(restTemplate.getForObject(url,String.class));
return result;
}
}
`
CodePudding user response:
In this case, you get what you ask for, which is a String. If the string being returned is JSON, you can either use an ObjectMapper to deserialize it into an object that represents the response or have RestTemplate do it for you.
Assuming the response payload looks like this:
{
"name": "some name"
}
Then you'd create a class to represent the response (using lombok for getters and setters):
@Getter
@Setter
public class ApiResponse {
private String name;
}
Then you can either let RestTemplate do the work for you:
ApiResponse result = restTemplate.getForObject(url, ApiResponse.class);
Or, handle it yourself
String result = restTemplate.getForObject(url,String.class);
ApiResponse apiResponse = new ObjectMapper().readerFor(ApiResponse.class).readValue(result);