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 aString
return type will cause aStringHttpMessageConverter
to write the value returned to the HTTP response body. ThisHttpMessageConverter
will produce acontent-type
oftext/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
orMappingJackson2HttpMessageConverter
which is set up to do pretty printing. Then change your handler method's return type toList<Locate>
and returnlocations
directly. TheseHttpMessageConverter
implementations produceapplication/json
which browsers should render literally.(
Gson
andObjectMapper
instances are thread safe. There's absolutely no reason to reinstantiate those classes for every request.)