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
@ResponseBodywith aStringreturn type will cause aStringHttpMessageConverterto write the value returned to the HTTP response body. ThisHttpMessageConverterwill produce acontent-typeoftext/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
GsonHttpMessageConverterorMappingJackson2HttpMessageConverterwhich is set up to do pretty printing. Then change your handler method's return type toList<Locate>and returnlocationsdirectly. TheseHttpMessageConverterimplementations produceapplication/jsonwhich browsers should render literally.(
GsonandObjectMapperinstances are thread safe. There's absolutely no reason to reinstantiate those classes for every request.)