5

I'm trying to pass a pretty printed JSON as a variable and have it display on an HTML page. in my .java file:

@RequestMapping(value = "/page1")
public String callback(Model model){
    String fruits = "{\n" +
                    "    \"fruit\": \"Apple\",\n" +
                    "    \"size\": \"Large\",\n" +
                    "    \"color\": \"Red\"\n" +
                    "}";
    JSONObject json_fruit = new JSONObject(fruits);
    System.out.println(json_fruit.toString(4));
    model.addAttribute("result", json_fruit.toString(4));
    return "page1";

in my page1.html file:

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8" />
    <title>Page1</title>
</head>
<body>
<p th:text="'JSON: ' + ${result}"></p>
</body>
</html>

when I System.out.println(), I get my json data formatted like this:

{
    "size": "Large",
    "color": "Red",
    "fruit": "Apple"
}

but on my html page:

JSON: { "size": "Large", "color": "Red", "fruit": "Apple" }

Is it possible to keep the newline characters in the HTML? How can I achieve this?

1 Answer 1

5

use:

<p th:text="'JSON: ' + ${result}"  style="white-space: pre"></p>
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, but I'm still getting the same results in the HTML page with this
I used your original answer to find that style="white-space: pre" preserves the white space and is exactly what I was looking for. The line I ended up using was <p th:text="'JSON: ' + ${result}" style="white-space: pre"></p> . Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.