Home > Java > javaTutorial > 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
Release: 2023-09-08 22:41:02
forward
1319 people have browsed it

我们如何使用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()
Copy after login

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);
   }
}
Copy after login

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"}
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template