How can we update an existing JSON data using javax.json API in Java?

JavaJSONObject Oriented ProgrammingProgramming

The JsonBuilderFactory interface is a factory to create JsonObjectBuilder instance and JsonObjectBuilder is a builder for creating JsonObject models from scratch. This interface initializes an empty JSON object model and provides methods to add name/value pairs to the object model and to return the resulting object. We can create a JsonObjectBuilder instance that can be used to build JsonObject using the createObjectBuilder() method.

Syntax

JsonObjectBuilder createObjectBuilder()

In the below example, We can update an existing JSON data with newly added data.

Example

import java.io.*;
import javax.json.*;
public class UpdateExistingJsonTest {
   public static void main(String[] args) throws Exception {
      String jsonString = "{\"id\":\"115\", \"name\":\"Raja\", \"address\":[{\"area\":\"Madhapur\", \"city\":\"Hyderabad\"}]}";
      StringReader reader = new StringReader(jsonString);
      JsonReader jsonReader = Json.createReader(reader);
      System.out.println("Existing JSON: \n" + jsonString);
      StringWriter writer = new StringWriter();
      JsonWriter jsonWriter = Json.createWriter(writer);
      JsonObject jsonObject = jsonReader.readObject();
      JsonBuilderFactory jsonBuilderFactory = Json.createBuilderFactory(null);
      JsonObjectBuilder jsonObjectBuilder = jsonBuilderFactory.createObjectBuilder();
      for(String key : jsonObject.keySet()) {
         jsonObjectBuilder.add(key, jsonObject.get(key));
      }
      jsonObjectBuilder.add("Contact Number", "9959984000");
      jsonObjectBuilder.add("Country", "India");
      jsonObject = jsonObjectBuilder.build();
      jsonWriter.writeObject(jsonObject);
      System.out.println("new JSON: \n" + jsonObject);
   }
}

Output

Existing JSON:
{"id":"115", "name":"Raja", "address":[{"area":"Madhapur", "city":"Hyderabad"}]}

new JSON:
{"id":"115","name":"Raja","address":[{"area":"Madhapur","city":"Hyderabad"}],"Contact Number":"9959984000","Country":"India"}
raja
Published on 01-Nov-2019 05:47:05
Advertisements