JSONWriter添加一个新的Line

问题描述 投票:1回答:1

我想将几个JSON对象写入txt文件。为了更好的视图,我希望每个对象都在不同的行中,并且存在我的问题:我不知道如何添加新行或分隔这些对象。这是我的代码:

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

我希望你能再次帮助我!

java json filewriter
1个回答
1
投票

您可以使用漂亮的打印选项:

   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(); 
    }
© www.soinside.com 2019 - 2024. All rights reserved.