1

I have a JSON file and I want to retrieve its content from a API call within a rest controller created in Java Spring Boot. I get the content of the .json file into a String and use the below method ( one of them ) in order to pretty print. If I system.out.println() the output, it gets pretty printed, but in the browser it is displayed roughly and with no indentation. I had more approaches :

String content = new String(Files.readAllBytes(resource.toPath()));

Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(content);
String prettyJsonString = gson.toJson(je);
System.out.println(prettyJsonString);

return prettyJsonString;

The other approach returns the same ugly output in browser, but it also adds "/r/n":

ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
String prettyJsonString = mapper.writeValueAsString(content);

return prettyJsonString;

Can anyone help me get the pretty output in browser as well?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Maria1995
  • 439
  • 1
  • 5
  • 21

2 Answers2

1

Formatting String for console output and for HTML output are two VERY different tasks. Method setPrettyPrinting() is for console printing. HTML browser will ignore "\n" symbols and will not respect multiple spaces replacing them with a single space etc. In general, it is usually a client-side task to format the output. But I delt once with this problem and wrote a method that takes a console-formatted string and converts it to Html formatted String. For instance, it replaces all "\n" symbols with br Html tags. It does some other things as well. I had some success with it, but sometimes some unexpected problems occurred. You are welcome to use it. The method is available in MgntUtils Open source library. Here is its JavaDoc. The library itself is available as Maven artifact here and on Github (including source code and JavaDoc) here. An article about the library is here. Your code would look like this:

String htmlString = TextUtils.formatStringToPreserveIndentationForHtml(jsonPrettyString);
Michael Gantman
  • 7,315
  • 2
  • 19
  • 36
1

I had this same problem and stumbled upon how to get it to pretty print in the browser. In your application.properties file, add these two lines:

# Preferred JSON mapper to use for HTTP message conversion.
spring.mvc.converters.preferred-json-mapper=gson

# Whether to output serialized JSON that fits in a page for pretty printing.
spring.gson.pretty-printing=true

Reference: https://www.callicoder.com/configuring-spring-boot-to-use-gson-instead-of-jackson/ Maybe related: https://stackoverflow.com/a/62044963