momal
momal

Reputation: 587

How to maintain the format of a string Java

So I'm parsing a JSON string to a java string and printing it. I'm using the following method to do that.

JSONParser parser=new JSONParser();
     Object obj = parser.parse(output);
     JSONObject jsonObject = (JSONObject) obj;
     String stdout= (String) jsonObject.get("Stdout");
     String stderr= (String) jsonObject.get("Stderr");

     out.print(stdout);
     out.print(stderr);

This is my JSON string:

{"Stdout":"/mycode.c: In function 'main':\n/mycode.c:8:5: error: expected ';' before 'return'\n     return 0;\r\n     ^\nsh: 1: ./myapp: not found\n","Stderr":"exit status 127"}

When I use System.out.print(stdout) and System.out.print(stdout) I get my desired format of output in the console. That is: console output

But now obviously I want it on my webpage so I do out.print(stdout) instead. But I don't get the desired format. Instead it just shows a single line. See picture: the webpage output

Any ideas how to fix this?

Upvotes: 0

Views: 547

Answers (1)

David Lavender
David Lavender

Reputation: 8321

Your webpage is HTML, so your /r/n aren't being treated as line breaks.

You could replace all of the \r\n with <br> tags to force new lines.

Or put your whole message in a <PRE> tag, which will render it as plain boring text and not HTML content. This is probably the safer option, because the content could contain other characters or text that might upset HTML parsing by the browser:

out.print("<PRE>" + stdout + "</PRE>");

Upvotes: 1

Related Questions