我想在 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 页面中显示它?
最佳答案
White space characters are usually collapsed in HTML (by default).这些字符包括换行符。将 JSON 转储到 <pre>
中.
<pre>
${response}
</pre>
关于java - 如何在 JSP 页面中显示 Pretty Print JSON 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14533530/