gpt4 book ai didi

java - JSONWriter 添加新行

转载 作者:行者123 更新时间:2023-11-30 05:46:27 25 4
gpt4 key购买 nike

我想将几个 JSON 对象写入一个 txt 文件。为了获得更好的 View ,我希望每个对象都位于不同的行中,但我的问题是:我不知道如何添加新行或分隔这些对象。这是我的代码:

       JsonObjectBuilder builder = Json.createObjectBuilder(); 
builder.add("Item", item);
builder.add("Choice 1", idchoice1);
builder.add("Choice 2", idchoice2);
builder.add("Choice 3", idchoice3);
JsonObject jo = builder.build();
try {
FileWriter fw = new FileWriter("SelectedChoice.txt", true);
JsonWriter jsonWriter = Json.createWriter(fw);
jsonWriter.writeObject(jo);
jsonWriter.close();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}

希望您能帮我解决我的问题。谢谢大家!

编辑:

现在我发现我的文件中的这种结构并不能解决我的问题。我想拆分保存在此 txt 文件中的几个 JSON 字符串,并且我的代码仅转换 JSON 对象中的第一个 JSON 字符串。这是我的代码:

    try {
FileReader fr = new FileReader("SelectedChoice.txt");
BufferedReader br = new BufferedReader(fr);

String zeile ="";

while((zeile = br.readLine())!=null) {
System.out.println(zeile);
JSONObject choice = new JSONObject(zeile);
System.out.println(choice);
}

br.close();
fr.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

希望您能再次帮助我!

最佳答案

您可以使用 pretty-print 选项:

   JsonObjectBuilder builder = Json.createObjectBuilder(); 
builder.add("Item", item);
builder.add("Choice 1", idchoice1);
builder.add("Choice 2", idchoice2);
builder.add("Choice 3", idchoice3);
JsonObject jo = builder.build();
try {
Map<String, Object> properties = new HashMap<>(1);
properties.put(JsonGenerator.PRETTY_PRINTING, true);
FileWriter fw = new FileWriter("SelectedChoice.txt", true);
JsonWriterFactory writerFactory = Json.createWriterFactory(properties);
JsonWriter jsonWriter = writerFactory.createWriter(fw);
jsonWriter.writeObject(jo);
jsonWriter.close();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}

关于java - JSONWriter 添加新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54746814/

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