Reputation: 30137
How to use pretty printing when writing to file?
package tests;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.stream.JsonWriter;
public class Try06 {
public static class V {
double x, y;
}
public static void main(String[] args) throws IOException {
GsonBuilder gb = new GsonBuilder();
gb = gb
.setPrettyPrinting()
.setVersion(1.0)
;
Gson gson0 = gb.create();
File file = new File("D:\\test.json");
System.out.println(gson0.toJson(new V()));
JsonWriter writer = new JsonWriter(new OutputStreamWriter(new FileOutputStream(file)));
gson0.toJson(new V(), V.class, writer);
writer.flush();
writer.close();
}
}
Also I noticed, that file is empty if not flushed. Should it flushed when exit?
Upvotes: 0
Views: 1442
Reputation: 2182
Explicitly setting a non-empty String indent helps:
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonWriter writer = new JsonWriter(new FileWriter(fileOut));
writer.setIndent(" "); // <-- without this the file is written without line-breaks and indents
gson.toJson(object, type, writer);
Have not had time to check Gson source, probably there's another way to solve it.
Upvotes: 2
Reputation: 2266
private void newline() throws IOException {
if (indent == null)
return;
out.write("\n"); //--- Your problem here!
int i = 1;
for (int size = stackSize; i < size; i++)
out.write(indent);
}
This part of the source of JsonWriter class. As a string delimiter is used '\n'. It is suitable for UNIX systems. But Windows is used for a new line '\r\n'.
How to solve your problem? Look at this:
DataOutputStream dos = new DataOutputStream(new FileOutputStream(file));
dos.writeBytes(gson0.toJson(new V()).replace("\n", "\r\n"));
dos.flush();
dos.close();
If you want system independed solution, then replace "\r\n" by this:
System.getProperty("line.separator");
or by this:
System.lineSeparator();
Upvotes: 0