Simon Hostettler Simon Hostettler - 1 month ago 10x
Java Question

BufferedWriter doesnt write JSON String correctly

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);

wr = new BufferedWriter(new FileWriter(dateiname));


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

It correctly prints it into the console :

But in my txt file it looks like this:

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


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");