How to add a JSON string to an existing JSON file in Java?

A Gson is a json library for Java and it can be used to generate a JSON. In the initial step, we can read a JSON file and parsing to a Java object then need to typecast the Java object to a JSonObject and parsing to a JsonArray. Then iterating this JSON array to print the JsonElement. We can create a JsonWriter class to write a JSON encoded value to a stream, one token at a time. Finally, a new JSON string can be written to an existing json file. 


import java.util.*;
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 =;
         Name name = new Name();
         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(, Name.class));
         gson.toJson(emps, Employees.class, jw);
         System.out.println("data added to an existing employee1.json file successfully");
      } catch(Exception e) {
// Name class
class Name {
   private String name;
   public String getName() {
      return name;
   public void setName(String name) { = name;
// Employees class
class Employees {
   List<Name> emps = new ArrayList<>();
   public List<Name> getEmployees() {
      return emps;
   public void addEmployee(Name name) {


The values of employee1.json file:
data added to an existing employee1.json file successfully

employee1.json file