【问题标题】:how to show Pretty Print JSON String in a JSP page如何在 JSP 页面中显示漂亮的打印 JSON 字符串
【发布时间】:2013-01-10 02:36:51
【问题描述】:

我想在 JSP 页面中显示一个 JSON 字符串。我正在使用 Spring MVC 框架。下面是代码

String result = restTemplate.getForObject(url.toString(), String.class);

ObjectMapper mapper = new ObjectMapper();
Object json = mapper.readValue(result, Object.class);

String indented = mapper.defaultPrettyPrintingWriter().writeValueAsString(json);

System.out.println(indented);//This print statement show correct way I need

model.addAttribute("response", (indented));

System.out.println(indented); 这一行打印出类似这样的内容-

{
  "attributes" : [ {
    "nm" : "ACCOUNT",
    "error" : "null SYS00019CancellationException in CoreImpl fetchAttributes\n java.util.concurrent.CancellationException\n\tat java.util.concurrent.FutureTask$Sync.innerGet(FutureTask.java:231)\n\tat java.util.concurrent.FutureTask.",
    "status" : "ERROR"
  } ]
}

这是我需要使用 JSP 页面显示的方式。但是当我像这样将它添加到模型时-

model.addAttribute("response", (indented));

然后在如下的 resultform.jsp 页面中显示出来-

    <fieldset>
        <legend>Response:</legend>
            <strong>${response}</strong><br />

    </fieldset>

我在浏览器上得到了类似的东西-

{ "attributes" : [ { "nm" : "ACCOUNT", "error" : "null    
SYS00019CancellationException in CoreImpl fetchAttributes\n 
java.util.concurrent.CancellationException\n\tat 
java.util.concurrent.FutureTask$Sync.innerGet(FutureTask.java:231)\n\tat 
java.util.concurrent.FutureTask.", "status" : "ERROR" } ] }

我不需要。不知道为什么会变成这样?我需要上面打印出来的方式是这样的。

{
  "attributes" : [ {
    "nm" : "ACCOUNT",
    "error" : "null SYS00019CancellationException in CoreImpl fetchAttributes\n java.util.concurrent.CancellationException\n\tat java.util.concurrent.FutureTask$Sync.innerGet(FutureTask.java:231)\n\tat java.util.concurrent.FutureTask.",
    "status" : "ERROR"
  } ]
}

谁能告诉我为什么会这样?以及如何以我需要的方式在 JSP 页面中显示它?

【问题讨论】:

    标签: java json jsp spring-mvc jackson


    【解决方案1】:

    White space characters are usually collapsed in HTML (by default). 这样的字符包括换行符。将 JSON 转储到 &lt;pre&gt;

    <pre>
    ${response}
    </pre>
    

    其他解决方案:https://stackoverflow.com/a/10474709/139010

    【讨论】:

    • 非常感谢马特。这正是我想要的。
    猜你喜欢
    • 2013-07-07
    • 1970-01-01
    • 1970-01-01
    • 2020-11-19
    • 2014-11-09
    • 2015-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多