【问题标题】:Prettyprinting Spring Boot JSON RESTful response in browser using thymeleaf使用 thymeleaf 在浏览器中打印 Spring Boot JSON RESTful 响应
【发布时间】:2019-10-24 16:35:51
【问题描述】:

我想以易于阅读的格式在浏览器中打印来自 RESTful 请求的 json 响应,同时保留 json 的换行符和缩进。

我当前的代码将 json 响应保存在一个字符串中,并在没有任何格式的情况下打印该字符串。

在 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";

}

在模板/print_response.html中

<body>
    [[${response}]] 
</body>

不需要进一步处理响应,它将仅用于在浏览器中的可视化。在控制器或模板中进行格式化更好吗?以及如何?

提前致谢!

【问题讨论】:

    标签: json spring-boot thymeleaf


    【解决方案1】:

    您可以尝试将响应字符串转换为 json 对象,然后再转换回缩进字符串:

    ObjectMapper objectMapper = new ObjectMapper();
    Object json = objectMapper.readValue(response, Object.class);
    String indented = objectMapper.writerWithDefaultPrettyPrinter()
                                   .writeValueAsString(json);
    

    【讨论】:

    • 谢谢你成功了!我不得不更改百里香模板以显示换行符: [(${#strings.replace( #strings.escapeXml( response ),T(java.lang.System).getProperty('line.separator'),'< br />')})] 我不确定是否有更直接的方法也可以显示缩进
    • 不,这是要走的路。我很乐意提供帮助,如果您能接受我的回答,我将不胜感激,谢谢
    猜你喜欢
    • 2020-10-04
    • 2017-11-09
    • 2017-03-23
    • 1970-01-01
    • 2011-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多