如何在JSP页面中显示Pretty Print JSON String

时间:2013-01-26 03:24:15

标签: 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页面中显示它?

1 个答案:

答案 0 :(得分:9)

White space characters are usually collapsed in HTML (by default).此类字符包括换行符。将JSON转储为<pre>

<pre>
${response}
</pre>

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