Friday, 13 September 2013

how to Concate the JSON Arary in java

This example is use for the concate or merge the more than one json Aray into signle json Array and for this example we need to download the json-lib-2.4-jdk15 library.

 import net.sf.json.JSONArray;  
 import net.sf.json.JSONException;  
 public class JsonConcateDemo {  
       public static JSONArray concatArray(JSONArray... arrs)throws JSONException   
       {  
         JSONArray result = new JSONArray();  
         for (JSONArray arr : arrs) {  
           for (int i = 0; i < arr.size(); i++) {  
             result.add(arr.get(i));  
           }  
         }  
         return result;  
       }  
       public static void main(String args[])  
       {  
            JSONArray jsonArray1=new JSONArray();  
            jsonArray1.add(0,"one");  
            jsonArray1.add(1,"two");  
            JSONArray jsonArray2=new JSONArray();  
            jsonArray2.add(0,"three");  
            jsonArray2.add(1,"four");  
            System.out.println("the JSONARRAY1:"+jsonArray1.toString());  
            System.out.println("the JSONARRAY2:"+jsonArray2.toString());  
            System.out.println("New concate array JSONArray1 and JSONArray2"+concatArray(jsonArray1,jsonArray2));  
       }  
 }  

The Output
 the JSONARRAY1:["one","two"]  
 the JSONARRAY2:["three","four"]  
 now new concate array JSONArray1 and JSONArray2["one","two","three","four"]