Pretty print JSON with Spring 4

585 views Asked by At

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?

1

There are 1 answers

0
Sotirios Delimanolis On

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.)