JsonBuilderFactory The interface is a factory used to create JsonObjectBuilder instances, while JsonObjectBuilder is a factory used to create instances from scratch Builder for creating JsonObject models. This interface initializes an empty JSON object model and provides methods to add name/value pairs to the object model and return the result object. We can use the createObjectBuilder() method to create a JsonObjectBuilder instance for building JsonObject .
JsonObjectBuilder createObjectBuilder()
In the following example, we can update the existing JSON data with the newly added data.
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); <strong> </strong>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); } }
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"}
The above is the detailed content of How can we update existing JSON data in Java using javax.json API?. For more information, please follow other related articles on the PHP Chinese website!