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

How can we merge two JSON objects in Java?

PHPz
Release: 2023-08-26 08:01:11
forward
1931 people have browsed it

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);
   }
}
Copy after login

Output

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

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template