Computer >> 컴퓨터 >  >> 프로그램 작성 >> Java

Java의 기존 JSON 파일에 JSON 문자열을 추가하는 방법은 무엇입니까?

<시간/>

지손 Java용 json 라이브러리이며 JSON을 생성하는 데 사용할 수 있습니다. 초기 단계에서 JSON 파일을 읽고 Java 객체로 구문 분석한 다음 타입캐스트 해야 합니다. JSonObject 에 대한 Java 개체 및 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 파일

Java의 기존 JSON 파일에 JSON 문자열을 추가하는 방법은 무엇입니까?