串联JSONArrays [英] Concatenate JSONArrays

查看:103
本文介绍了串联JSONArrays的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在org.json包下使用 JSONArray . /p>

我的第一个JSONArray是这样的:

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

和第二

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

所以我想将新的JSONArray附加到我的第一个JSONArray中.

我正在使用Java和Android.我听说过 google-gson 库,但是我不知道它是否可以帮助我与否,但我不希望我的Android应用程序具有任何其他依赖关系.

解决方案

我会尝试这样的事情:

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

我现在没有要测试的编译器,但是您可以尝试一下它,看看它是否有效(或者至少可以让您知道如何执行该操作).

编辑

此版本可以合并多个数组(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;
}

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.

解决方案

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

这篇关于串联JSONArrays的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆