Home  >  Article  >  Java  >  How can we update existing JSON data in Java using javax.json API?

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

PHPz
PHPzforward
2023-09-08 22:41:021239browse

我们如何使用javax.json API在Java中更新现有的JSON数据?

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 .

Syntax

JsonObjectBuilder createObjectBuilder()

In the following example, we can update the existing JSON data with the 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);
<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);
   }
}

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"}

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete