Home  >  Article  >  Java  >  How can we merge two JSON objects in Java?

How can we merge two JSON objects in Java?

PHPz
PHPzforward
2023-08-26 08:01:111862browse

How can we merge two JSON objects in Java?

JSON is a lightweight data exchange format. The format of JSON is key-value pairs. JSONObject can parse text in a string to generate map-like objects and supports the java.util.Map interface. We can merge two JSON objects in Java using org.json.simple.JSONObject.

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

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"}

The above is the detailed content of How can we merge two JSON objects in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete