簡體   English   中英

JSONWriter 添加新行

[英]JSONWriter add a new Line

我想將幾個 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();
   }

我希望你能再次幫助我!

您可以使用漂亮的打印選項:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM