2011-01-04 22 views
22

Ich verwende JSONArray unter dem org.json Paket.Concate JSONArray

Mein erster JSONArray ist wie:

[[ "249404", "VPR249404"], [ "249403", "VPR249403"], [ "249391", "M249391"]]

und Zweite

[[ "249386", "M249386"], [ "249385", "M249385 (I)"], [ "249384", "I249384"]]

Also möchte ich neues JSONArray an mein erstes JSONArray anhängen.

Ich arbeite an Java und Android. Ich habe über google-gson Bibliothek gehört, aber ich weiß nicht, ob es mir helfen kann oder nicht, aber ich möchte keine andere Abhängigkeit in meiner Android-Anwendung.

Antwort

45

Ich würde so etwas wie dies versuchen:

private JSONArray concatArray(JSONArray arr1, JSONArray arr2) 
     throws JSONException { 
    JSONArray result = new JSONArray(); 
    for (int i = 0; i < arr1.length(); i++) { 
     result.put(arr1.get(i)); 
    } 
    for (int i = 0; i < arr2.length(); i++) { 
     result.put(arr2.get(i)); 
    } 
    return result; 
} 

Ich teste keinen Compiler jetzt müssen, aber man kann es versuchen und sehen, ob es funktioniert (oder zumindest, es gibt Sie eine Idee, wie es geht).

EDIT

Diese Version könnte mehrere Arrays (concatArray(arr1, arr2, arr3)) verketten:

private JSONArray concatArray(JSONArray... arrs) 
     throws JSONException { 
    JSONArray result = new JSONArray(); 
    for (JSONArray arr : arrs) { 
     for (int i = 0; i < arr.length(); i++) { 
      result.put(arr.get(i)); 
     } 
    } 
    return result; 
} 
+1

Wie doppelte Werte zu halten, nur einmal? –