简体   繁体   English

使用Spring 4漂亮地打印JSON

[英]Pretty print JSON with Spring 4

I have a controller class that looks like: 我有一个控制器类,看起来像:

@RequestMapping(value="/enter/two-factor/blacklist", method = RequestMethod.GET, produces = "application/json")
public @ResponseBody String getBlacklist(int days) {
    List<Honey> honey = honeyService.fetchAllPings(days);
    List<Locate> locations = honeyService.parseDistinctLocations(honey);
    return GeneralUtil.convertToJson(locations);
}

The 'GeneralUtil.convertToJson()' method returns a pretty-print string with this code: 'GeneralUtil.convertToJson()'方法使用以下代码返回漂亮的字符串:

public static String convertToJson(List<Locate> locations){
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    String json = "";
    try {
        json = gson.toJson(new Blacklist(locations));
    } catch (Exception e){
        e.printStackTrace();
    }
    JsonParser jp = new JsonParser();
    JsonElement je = jp.parse(json);
    String prettyJsonString = gson.toJson(je);
    System.out.println(prettyJsonString);
    return prettyJsonString;
}

However, when the page renders, the JSON is not pretty-printed. 但是,当页面呈现时,JSON的打印效果不佳。 What am I missing? 我想念什么?

You're overlooking the fact that @ResponseBody with a String return type will cause a StringHttpMessageConverter to write the value returned to the HTTP response body. 你可以俯瞰事实@ResponseBodyString返回类型会导致StringHttpMessageConverter写的值返回HTTP响应体。 This HttpMessageConverter will produce a content-type of text/plain . HttpMessageConverter将产生text/plaincontent-type I believe browsers don't render new line characters or trim whitespace between them. 我认为浏览器不会渲染换行符或修剪它们之间的空格。 Your pretty printing gets lost. 您漂亮的印刷品迷路了。

What you should do is register your own GsonHttpMessageConverter or MappingJackson2HttpMessageConverter which is set up to do pretty printing. 您应该做的是注册自己的GsonHttpMessageConverterMappingJackson2HttpMessageConverter ,将其设置为进行漂亮的打印。 Then change your handler method's return type to List<Locate> and return locations directly. 然后将您的处理程序方法的返回类型更改为List<Locate>并直接返回locations These HttpMessageConverter implementations produce application/json which browsers should render literally. 这些HttpMessageConverter实现实现了application/json ,浏览器应按HttpMessageConverter呈现。

( Gson and ObjectMapper instances are thread safe. There's absolutely no reason to reinstantiate those classes for every request.) GsonObjectMapper实例是线程安全的。绝对没有理由为每个请求重新实例化这些类。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM