How can we merge two JSON arrays in Java?


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

We can merge two JSON arrays using the addAll() method (inherited from interface java.util.List) in the below program.

Example

import org.json.simple.JSONArray;
import java.io.IOException;
public class MergeJSONArraysTest {
   public static void main(String[] args) throws IOException {
      JSONArray jsonArray1 = new JSONArray(); // first json array
      jsonArray1.add("Java");
      jsonArray1.add("Python");
      jsonArray1.add("Spark");
      JSONArray jsonArray2 = new JSONArray(); // second json array
      jsonArray2.add("Selenium");
      jsonArray2.add("ServiceNow");
      jsonArray1.addAll(jsonArray2); // merge two arrays using addAll() method
      System.out.println(jsonArray1);
   }
}

Output

["Java","Python","Spark","Selenium","ServiceNow"]

Updated on: 04-Jul-2020

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements