简体   繁体   中英

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:

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. 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. This HttpMessageConverter will produce a content-type of text/plain . 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. Then change your handler method's return type to List<Locate> and return locations directly. These HttpMessageConverter implementations produce application/json which browsers should render literally.

( Gson and ObjectMapper instances are thread safe. There's absolutely no reason to reinstantiate those classes for every request.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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