如何在 Java 中將 JSON 字串新增到現有 JSON 檔案?


Gson 是一個針對 Java 的 json 庫,可用於生成 JSON。在初始步驟中,我們可以讀取一個 JSON 檔案並將其解析為一個 Java 物件,然後需要型別轉換 Java 物件為JSonObject ,並解析為JsonArray。然後迭代此 JSON 陣列以列印JsonElement。我們可以建立一個JsonWriter 類,一次一個令牌地將 JSON 編碼值寫入流。最後,可以將一個新的 JSON 字串寫入現有的 json 檔案。 

示例

import java.io.*;
import java.util.*;
import com.google.gson.*;
import com.google.gson.stream.*;
import com.google.gson.annotations.*;
public class JSONFilewriteTest {
   public static String nameRead;
   public static void main(String[] args) {
      try {
         JsonParser parser = new JsonParser();
         Object obj = parser.parse(new FileReader("employee1.json"));
         JsonObject jsonObject = (JsonObject) obj;
         System.out.println("The values of employee1.json file:\n" + jsonObject);
         JsonArray msg = (JsonArray)jsonObject.get("emps");
         Iterator<JsonElement> iterator = msg.iterator();
         while(iterator.hasNext()) {
            nameRead = iterator.next().toString();
            System.out.println(nameRead);
         }
         Name name = new Name();
         name.setName("Vamsi");
         Gson gson = new Gson();
         String json = gson.toJson(name);

         FileWriter file = new FileWriter("employee1.json", false);
         JsonWriter jw = new JsonWriter(file);
         iterator = msg.iterator();
         Employees emps = new Employees();
         while(iterator.hasNext()) {
            emps.addEmployee(gson.fromJson(iterator.next().toString(), Name.class));
         }
         emps.addEmployee(name);
         gson.toJson(emps, Employees.class, jw);
         file.close();
         System.out.println("data added to an existing employee1.json file successfully");
      } catch(Exception e) {
         e.printStackTrace();
      }
   }
}
// Name class
class Name {
   @Expose
   private String name;
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
}
// Employees class
class Employees {
   @Expose
   List<Name> emps = new ArrayList<>();
   public List<Name> getEmployees() {
      return emps;
   }
   public void addEmployee(Name name) {
      this.emps.add(name);
   }
}

輸出

The values of employee1.json file:
{"emps":[{"name":"Adithya"},{"name":"Jai"}]}
{"name":"Adithya"}
{"name":"Jai"}
data added to an existing employee1.json file successfully


employee1.json 檔案

更新時間:06-Jul-2020

6K+ 次瀏覽

開啟您的職業生涯

完成本課程獲得認證

開始
廣告
© . All rights reserved.