gpt4 book ai didi

java - Gson 错误?如果写入文件则忽略 PrettyPrinting

转载 作者:行者123 更新时间:2023-12-01 13:17:21 25 4
gpt4 key购买 nike

写入文件时如何使用 pretty-print ?

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



}
}

我还注意到,如果不刷新该文件就是空的。退出时是否应该刷新?

最佳答案

显式设置非空字符串缩进有助于:

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

还没来得及查Gson源码,可能还有别的办法解决。

关于java - Gson 错误?如果写入文件则忽略 PrettyPrinting,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22360346/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com