How can we merge two JSON objects in Java?

A JSON is a lightweight data-interchange format and the format of JSON is a key with value pair. The JSONObject can parse a text from a String to produce a map-like object and supports java.util.Map interface. We can use org.json.simple.JSONObject to merge two JSON objects in Java.

We can merge two JSON objects using the putAll() method (inherited from interface java.util.Map) in the below program.


import java.util.Date;
import org.json.simple.JSONObject;
public class MergeJsonObjectsTest {
   public static void main(String[] args) {
      JSONObject jsonObj = new JSONObject(); // first json object
      jsonObj.put("Name", "Adithya");
      jsonObj.put("Age", 25);
      jsonObj.put("Address", "Hitech City");
      JSONObject jsonObj1 = new JSONObject(); // second json object
      jsonObj1.put("City", "Hyderabad");
      jsonObj1.put("DOB", new Date(104, 3, 6));
      jsonObj.putAll(jsonObj1); // merging of first and second json objects


{"Address":"Hitech City","DOB":Tue Apr 06 00:00:00 IST 2004,"City":"Hyderabad","