【问题标题】:Java Filter JsonArray with Integer Array for parameterJava过滤JsonArray与整数数组作为参数
【发布时间】:2016-08-23 07:55:17
【问题描述】:

我的目标是使用ListIntegers 过滤JSONArray 作为参数:

JSONObject record1 = new JSONObject();
record1.put("id", "44");
record1.put("name", "somename");

我当前创建新的JSONArray 并以 id 作为参数的函数:

 private JSONArray modifyJsonArray(JSONArray array, final Integer param) throws JSONException {
        List<JSONObject> jsons = new ArrayList<JSONObject>();
        mainJsons = new ArrayList<JSONObject>();
        for (int i = 0; i < array.length(); i++) {
            Integer id = Integer.parseInt(array.getJSONObject(i).getString("id"));
            mainJsons.add(array.getJSONObject(i));
            if (id == param) {
                jsons.add(array.getJSONObject(i));
            }
        }
        return new JSONArray(jsons);
    }

我想传递 List&lt;Integer&gt; 而不是 final Integer param

【问题讨论】:

  • 好的,有什么问题?

标签: java arrays json list


【解决方案1】:

使用两个 for 循环解决了问题:

  private JSONArray modifyJsonArray(JSONArray array, final List<Integer> param) throws JSONException {
    List<JSONObject> jsons = new ArrayList<JSONObject>();
    mainJsons = new ArrayList<JSONObject>();
    for (int i = 0; i < array.length(); i++) {
        Integer id = Integer.parseInt(array.getJSONObject(i).getString("id"));
        mainJsons.add(array.getJSONObject(i));
        for (int j = 0; j < param.size(); j++){
            if (statusId == param.get(j)) {
                jsons.add(array.getJSONObject(i));
            }
        }
    }
    return new JSONArray(jsons);
}

【讨论】:

    【解决方案2】:

    只需传递一个数组参数并放置项目:

     private JSONArray modifyJsonArray(JSONArray a,  int[] arr) throws JSONException {
            for(int i:arr){
                a.put(i);
            }
            return a;
    }
    

    【讨论】:

      猜你喜欢
      • 2015-11-24
      • 2010-10-08
      • 2023-03-22
      • 2022-01-22
      • 1970-01-01
      • 2023-04-01
      • 2017-10-22
      • 2016-09-18
      • 2017-05-01
      相关资源
      最近更新 更多