0

I wrote a code that gets a JSON text from a website and formats it so it is easier to read. My problem with the code is:

public static void gsonFile(){
  try {
    re = new BufferedReader(new FileReader(dateiname));
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    JsonParser jp = new JsonParser();
    String uglyJSONString ="";
    uglyJSONString = re.readLine();
    JsonElement je = jp.parse(uglyJSONString);  
    String prettyJsonString = gson.toJson(je);
    System.out.println(prettyJsonString);

    wr = new BufferedWriter(new FileWriter(dateiname));
    wr.write(prettyJsonString);

    wr.close();
    re.close();

} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
}

It correctly prints it into the console : http://imgur.com/B8MTlYW.png

But in my txt file it looks like this: http://imgur.com/N8iN7dv.png

What can I do so it correctly prints it into the file? (separated by new lines)

Anon Ymous
  • 167
  • 1
  • 2
  • 14

4 Answers4

2

Gson uses \n as line delimiter (as can be seen in the newline method here).

Since Notepad does not understand \n you can either open your result file with another file editor (Wordpad, Notepad++, Atom, Sublime Text, etc.) or replace the \n by \r\n before writing it:

prettyJsonString = prettyJsonString.replace("\n", "\r\n");
Raphaël
  • 3,646
  • 27
  • 28
2

FileReader and FileWriter are old utility classes that use the platform encoding. This gives non-portable files. And for JSON one ordinarily uses UTF-8.

Path datei = Paths.get(dateiname);
re = Files.newBufferedReader(datei, StandardCharsets.UTF_8);

Or

List<String> lines = Files.readAllLines(datei, StandardCharsets.UTF_8);
// Without line endings as usual.

Or

String text = new String(Files.readAllBytes(datei), StandardCharsets.UTF_8);

And later:

Files.write(text.getBytes(StandardCharsets.UTF_8));
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
1

It is problem with your text editor. Not with text. It incorrectly process new line character.

I suppose it expect CR LF(Windows way) symbols and Gson generate only LF symbol (Unix way).

talex
  • 17,973
  • 3
  • 29
  • 66
  • Try opening it with another editor (I know that you can see the whitespace characters with notepad++ for instance) and check the layout and whitespace there. – Timo Sep 05 '16 at 15:06
1

After a quick search this topic might come handy.

Strings written to file do not preserve line breaks

Also, opening in another editor like the others said will help too

Community
  • 1
  • 1