Java-处理基于密钥的Json数组

时间:2016-07-21 06:07:54

标签: java android arrays json

我将此字符串(来自webservice)转换为JSONArray,

[{
    "textinput": [{
        "position": 0,
        "dependency": "no",
        "id": 0,
        "Itype": "textinput"
    }, {
        "position": 2,
        "dependency": "no",
        "id": 1,
        "Itype": "textinput"
    }]
}, {
    "textarea": [{
        "position": 1,
        "type": "textarea",
        "dependency": "no",
        "id": 0
    }]
}]

我需要根据键按升序对数组进行排序 - " position" 我使用的是org.json库,下面的代码是到目前为止使用的代码

JSONArray sortedJsonArray = new JSONArray();
List<JSONObject> jsonList = new ArrayList<JSONObject>();
for (int i = 0; i < jsonArray.length(); i++) {
    jsonList.add(jsonArray.getJSONObject(i));
}

Collections.sort( jsonList, new Comparator<JSONObject>() {

    public int compare(JSONObject a, JSONObject b) {
        String valA = new String();
        String valB = new String();

        try {
            valA = (String) a.get("position");
            valB = (String) b.get("position");
        } 
        catch (JSONException e) {
            //do something
        }

        return valA.compareTo(valB);
    }
});

for (int i = 0; i < jsonArray.length(); i++) {
    sortedJsonArray.put(jsonList.get(i));
}

AALso尝试了网站中的其他链接。 请帮忙

1 个答案:

答案 0 :(得分:1)

尝试使用TreeMap,它会自动为您排序数组。你所要做的就是做位置&#34; TreeMap的密钥和JSONObject的值。树形图将按键的升序排列值。然后您可以从树形图中检索JSONObject值。

    private TreeMap<Integer,JSONObject> sortedarray = new TreeMap<Integer,JONObject>();


    for (int i = 0; i < jsonArray.length(); i++) {
        try {
            sortedarray.put(Integer.parseInt(jsonArray.getJSONObject(i).get("position")+""),jsonArray.getJSONObject(i));

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

现在,如果你想让它只是一个jsonArray ..

    JSONArray sortedJsonArray = new JSONArray();
    for(int x = 0; x<sortedarray.size();x++)
        {

            //assuming that positions you get in JSON are always complete like 1,2,3,4,....,10,...,100.
              sortedJsonArray.put(sortedarray.get(x));

            //assuming that positions you get in JSON are not always complete like 1,3,4,..,10,13,...,100.( misses a few numbers in between like 2 and 11 in this case)  
            sortedJsonArray.put(sortedarray.get(Integer.parseInt(advanceplay.get(advanceplay.keySet().toArray()[i]))));

        }