使用JavaSpringBootEleaf显示来自变量的漂亮打印JSON
我试图将一个打印精美的JSON作为变量传递,并将其显示在HTML页面上。 在my.java文件中:使用JavaSpringBootEleaf显示来自变量的漂亮打印JSON,java,html,spring-boot,thymeleaf,Java,Html,Spring Boot,Thymeleaf,我试图将一个打印精美的JSON作为变量传递,并将其显示在HTML页面上。 在my.java文件中: @RequestMapping(value = "/page1") public String callback(Model model){ String fruits = "{\n" + " \"fruit\": \"Apple\",\n" +
@RequestMapping(value = "/page1")
public String callback(Model model){
String fruits = "{\n" +
" \"fruit\": \"Apple\",\n" +
" \"size\": \"Large\",\n" +
" \"color\": \"Red\"\n" +
"}";
JSONObject json_fruit = new JSONObject(fruits);
System.out.println(json_fruit.toString(4));
model.addAttribute("result", json_fruit.toString(4));
return "page1";
在my page1.html文件中:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title>Page1</title>
</head>
<body>
<p th:text="'JSON: ' + ${result}"></p>
</body>
</html>
但在我的html页面上:
JSON: { "size": "Large", "color": "Red", "fruit": "Apple" }
是否可以在HTML中保留换行符?如何实现这一点?使用:
<p th:text="'JSON: ' + ${result}" style="white-space: pre"></p>
谢谢,但我在HTML页面上仍然得到了与此相同的结果。我使用您的原始答案发现style=“white space:pre”
保留了空白,这正是我所寻找的。我最后使用的行是
。非常感谢。
<p th:text="'JSON: ' + ${result}" style="white-space: pre"></p>