What is the method for merging JsonObject in Java?
In Java, you can use the JsonMergePatch class to merge JSONObjects.
Here is a sample code:
import org.json.JSONObject;
import javax.json.Json;
import javax.json.JsonMergePatch;
import javax.json.JsonValue;
public class JsonMergeExample {
public static void main(String[] args) {
JSONObject baseJson = new JSONObject("{\"name\":\"John\", \"age\":25}");
JSONObject patchJson = new JSONObject("{\"age\":30, \"city\":\"New York\"}");
// 将JSONObject转换为JsonMergePatch
JsonMergePatch mergePatch = Json.createMergePatch(patchJson.toString());
// 应用合并补丁
JsonValue mergedJson = mergePatch.apply(baseJson);
System.out.println("合并后的JSON:" + mergedJson);
}
}
In the example above, we start by converting two JSONObject into JsonMergePatch. Then, we use the apply() method to apply the merge patch to the base JSONObject, resulting in the merged JSON. Finally, we print out the merged JSON.
Please note that using JsonMergePatch requires adding a dependency for the javax.json library.