1

我有一个 jArray 和来自该 jArray 的字符串“message2”:

[{"date":"2012","count":"1","message" : "message1"}, {"date":"2011","count":"2","message":"message2"}}

我如何确定来自哪个 JSONObject“message2”,然后确定与该消息相关的“计数”?

伪代码:

x = count of jArray element that contains the string "message2"
4

1 回答 1

0

如果 JSONArray 未排序,这是基本方法:

try {
    //JSONArray jArray = new JSONArray();
    JSONObject item;
    boolean found = false;
    int length = jArray.length();
    String key = "message";
    String orphan = "message2"; // Let's find where you belong

    for(int index = 0; index < length; index++) {
        item = jArray.getJSONObject(index);
        if(item.getString(key).equals(orphan)) {
            found = true;
            break;
        }
    }

    if(found) {
        // item references the JSONObject that you want
    }
    else {
        // No match found
    }
}
catch(JSONException e) {
    // Try to handle the error gracefully
}
于 2012-06-17T03:44:01.983 回答