Reputation: 584
I would like to print the json response from a RESTful request in the browser in a easy human readable format, keeping json's linebreaks and indentations.
My current code saves the json response in a String and prints the string without any formatting.
In RESTFulController.java
@Controller
public class RESTFulControllerController {
@RequestMapping("myrequest")
public String myRequest(Model model) {
//--> Initializations
RestTemplate rest_template= new RestTemplate();
String url = "https://example.com/api";
//--> Create http request
HttpHeaders headers = new HttpHeaders();
MultiValueMap<String, String> body_map = new LinkedMultiValueMap<>();
body_map.add("resource_id", "value_of_resource_id");
HttpEntity<MultiValueMap<String, String>> request_entity = new HttpEntity<>(body_map, headers);
//--> Post http request
String response = rest_template.postForObject(url, request_entity, String.class);
//--> Add data for display
model.addAttribute("response", response);
return "print_response";
}
In templates/print_response.html
<body>
[[${response}]]
</body>
There is no need for further processing the response, it will be used only for its visualization in the browser. Is it better to do the formatting in the controller or in the template? and how?
Thanks in advance!
Upvotes: 0
Views: 1436
Reputation: 36123
You can try to convert your response string to a json object and then back to a indented string:
ObjectMapper objectMapper = new ObjectMapper();
Object json = objectMapper.readValue(response, Object.class);
String indented = objectMapper.writerWithDefaultPrettyPrinter()
.writeValueAsString(json);
Upvotes: 2