26

I am using JSONArray under the org.json Package.

My first JSONArray is like:

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

and Second

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

So I'd like to append new JSONArray to my first JSONArray.

I am working on Java and Android. I have heard about google-gson library, but I don't know whether it can help me or not but I don't want any other dependency in my Android Application.

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
Vikas
  • 24,082
  • 37
  • 117
  • 159

3 Answers3

52

I would try something like this:

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

I don't have a compiler right now to test, but you can give it a try and see if it works (or, at least, it gives you an idea of how to do it).

EDIT

This version could concat multiple arrays (concatArray(arr1, arr2, arr3)):

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;
}
Cristian
  • 198,401
  • 62
  • 356
  • 264
-1

try this:

private JSONArray concatArray(@NotNull JSONArray jsArr1, @NotNull JSONArray jsArr2) {
    List<Object> list = jsArr1.toList();
    list.addAll(jsArr2.toList());
    return new JSONArray(list);
}
Rocas Yeh
  • 188
  • 2
  • 6
  • org.json.JSONException: JSONArray initial value should be a string or collection or array. at org.json.JSONArray.(JSONArray.java:203) – FilippoG Apr 16 '20 at 11:07
-3

Use ...

jarray1.addAll(jarray2);