Remove all elements except one from JSONArray of JSONObjects

后端 未结 3 731
离开以前
离开以前 2021-01-27 00:56

I have a JSONArray (org.json) like this:

[
    { \"a\": \"a\" },
    { \"b\": \"a\" },
    { \"c\": \"a\" },
    { \"d\": \"a\" },
    { \"e\": \"a\" },
    { \"         


        
3条回答
  •  清酒与你
    2021-01-27 00:56

    If you want to avoid using type casts, try:

    private static final String JSON = "{\"arr\": [" +
            "{\"z\": \"z\"}," +
            "{\"a\": \"a\"}," +
            "{\"b\": \"b\"}," +
            "{\"c\": \"c\"}" +
            "]}";
    . . .
    JSONObject jsonObject = new JSONObject(JSON);
    JSONArray array = jsonObject.getJSONArray("arr");
    JSONArray filtered = new JSONArray();
    
    for (int i = 0; i < array.length(); i++) {
        JSONObject sub = array.getJSONObject(i);
        if (sub.has("a")) {
             filtered.put(sub);
         }
    }
    
    jsonObject.put("arr", filtered);
    System.out.println(jsonObject.toString());
    

    Result:

    {"arr":[{"a":"a"}]}
    

提交回复
热议问题