java - 如何在 JSP 页面中显示 Pretty Print JSON 字符串

标签 java json jsp spring-mvc jackson

我想在 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>

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

关于java - 如何在 JSP 页面中显示 Pretty Print JSON 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14533530/

相关文章:

javascript - 将带有列表的 JS 对象转换为 C# 列表

javascript - 在不使用任何插件的情况下在 JavaScript 中将数组分组和映射为不同的格式

java - jsp 页面中的 swf 播放器

java - JPA:2个应用程序需要更新一个对象

java - 为什么在迭代之间 hibernate 会导致循环中的操作比不 hibernate 的情况花费更长的时间

java - 从文件中读取可变行数

java - 如何使用对象字段本身给定的格式解析输入对象日期字段

java - Google Protocol Buffer 和 servlet

java - 如何使用和存储用户偏好

java - Play Framework 中的发布请求中的表单值为null