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.

Example

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
      System.out.println(jsonObj);
   }
}

Output

{"Address":"Hitech City","DOB":Tue Apr 06 00:00:00 IST 2004,"City":"Hyderabad","
Age":25,"Name":"Adithya"}

Updated on: 04-Jul-2020

13K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements