JsonBuilderFactory 介面是用來建立JsonObjectBuilder 實例的工廠,而JsonObjectBuilder 則是一個用於從頭建立JsonObject 模型的建構器。此介面初始化一個空的JSON 物件模型,並提供方法來在物件模型中新增名稱/值對並傳回結果物件。我們可以使用createObjectBuilder()方法來建立一個JsonObjectBuilder 實例,用來建構JsonObject 。
JsonObjectBuilder createObjectBuilder()
在下面的範例中,我們可以使用新新增的資料來更新現有的JSON資料。
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"}
以上是我們如何使用javax.json API在Java中更新現有的JSON資料?的詳細內容。更多資訊請關注PHP中文網其他相關文章!