小编mEE*_*Ezy的帖子

使用 Java Spring boot Thymeleaf 从变量中显示漂亮的打印 JSON

我正在尝试将打印精美的 JSON 作为变量传递,并将其显示在 HTML 页面上。在我的 .java 文件中:

@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";
Run Code Online (Sandbox Code Playgroud)

在我的 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>
Run Code Online (Sandbox Code Playgroud)

当我 System.out.println() 时,我得到的 json 数据格式如下:

{
    "size": "Large",
    "color": "Red",
    "fruit": "Apple"
}
Run Code Online (Sandbox Code Playgroud)

但在我的 html …

html java thymeleaf spring-boot

5
推荐指数
1
解决办法
3678
查看次数

标签 统计

html ×1

java ×1

spring-boot ×1

thymeleaf ×1