【问题标题】:How do I remove a specific element from a JSONArray?如何从 JSONArray 中删除特定元素?
【发布时间】:2012-02-07 21:13:38
【问题描述】:

我正在构建一个应用程序,在该应用程序中我从服务器请求一个 PHP 文件。这个 PHP 文件返回一个以 JSONObjects 作为其元素的 JSONArray,例如,

[ 
  {
    "uniqid":"h5Wtd", 
    "name":"Test_1", 
    "address":"tst", 
    "email":"ru_tst@tst.cc", 
    "mobile":"12345",
    "city":"ind"
  },
  {...},
  {...},
  ...
]

我的代码:

/* jArrayFavFans is the JSONArray i build from string i get from response.
   its giving me correct JSONArray */
JSONArray jArrayFavFans=new JSONArray(serverRespons);
for (int j = 0; j < jArrayFavFans.length(); j++) {
  try {
    if (jArrayFavFans.getJSONObject(j).getString("uniqid").equals(id_fav_remov)) {
      //jArrayFavFans.getJSONObject(j).remove(j); //$ I try this to remove element at the current index... But remove doesn't work here ???? $
      //int index=jArrayFavFans.getInt(j);
      Toast.makeText(getParent(), "Object to remove...!" + id_fav_remov, Toast.LENGTH_SHORT).show();
    }
  } catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
  }
}

如何从这个 JSONArray 中删除特定元素?

【问题讨论】:

    标签: java android arrays json


    【解决方案1】:

    试试这个代码

    ArrayList<String> list = new ArrayList<String>();     
    JSONArray jsonArray = (JSONArray)jsonObject; 
    
    if (jsonArray != null) { 
       int len = jsonArray.length();
       for (int i=0;i<len;i++){ 
        list.add(jsonArray.get(i).toString());
       } 
    }
    //Remove the element from arraylist
    list.remove(position);
    //Recreate JSON Array
    JSONArray jsArray = new JSONArray(list);
    

    编辑: 使用ArrayList 会将"\" 添加到键和值中。所以,使用JSONArray 本身

    JSONArray list = new JSONArray();     
    JSONArray jsonArray = new JSONArray(jsonstring); 
    int len = jsonArray.length();
    if (jsonArray != null) { 
       for (int i=0;i<len;i++)
       { 
           //Excluding the item at position
            if (i != position) 
            {
                list.put(jsonArray.get(i));
            }
       } 
    }
    

    【讨论】:

    • if (jsonArray != null) 在您的编辑示例中没有意义,因为它永远不会为空。即使会,它前面的行也会抛出 NullPointerException。原始样本也是如此。
    【解决方案2】:

    如果有人返回有关 Android 平台的相同问题,如果您的目标是 Android API-18 或更低版本,则不能使用内置的 remove() 方法。 remove() 方法是在 API 级别 19 上添加的。因此,最好的办法是扩展 JSONArray 以为 remove() 方法创建兼容的覆盖。

    public class MJSONArray extends JSONArray {
    
        @Override
        public Object remove(int index) {
    
            JSONArray output = new JSONArray();     
            int len = this.length(); 
            for (int i = 0; i < len; i++)   {
                if (i != index) {
                    try {
                        output.put(this.get(i));
                    } catch (JSONException e) {
                        throw new RuntimeException(e);
                    }
                }
            } 
            return output;
            //return this; If you need the input array in case of a failed attempt to remove an item.
         }
    }
    

    编辑 正如 Daniel 指出的那样,默默地处理错误是一种不好的风格。代码改进。

    【讨论】:

    • 这是不好的编码风格。如果发生错误,元素不会被删除,但调用代码没有机会知道这一点。更好的方法是使用try..catch,而是在函数头中使用throws JSONException
    • @DanielAlder remove 方法不能抛出异常,因为被覆盖的方法不这样做。
    • 好的,在这种情况下,我会放一个throw new RuntimeException(e)(或InternalError)而不是e.printStackTrace();return this;——只是为了案例
    • 不建议扩展默认类。最好在您使用它的类中创建remove() 方法。
    【解决方案3】:
    public static JSONArray RemoveJSONArray( JSONArray jarray,int pos) {
    
    JSONArray Njarray=new JSONArray();
    try{
    for(int i=0;i<jarray.length();i++){     
        if(i!=pos)
            Njarray.put(jarray.get(i));     
    }
    }catch (Exception e){e.printStackTrace();}
    return Njarray;
    
    }
    

    【讨论】:

      【解决方案4】:
       JSONArray jArray = new JSONArray();
      
          jArray.remove(position); // For remove JSONArrayElement
      

      注意:-如果remove() 不在JSONArray 中,那么...

      Android (4.4) 的 API 19 实际上允许这种方法。

      调用需要 API 级别 19(当前最低为 16):org.json.JSONArray#remove

      右键单击项目转到属性

      从左侧站点选项中选择 Android

      然后选择大于 API 19 的 Project Build Target

      希望对你有帮助。

      【讨论】:

        【解决方案5】:

        我猜你使用的是 Me 版本,我建议在你的代码 (JSONArray.java) 中手动添加这个函数块:

        public Object remove(int index) {
            Object o = this.opt(index);
            this.myArrayList.removeElementAt(index);
            return o;
        }
        

        在 java 版本中他们使用 ArrayList,在 ME 版本中他们使用 Vector。

        【讨论】:

          【解决方案6】:

          你可以使用反射

          一个中文网站提供了相关的解决方案:http://blog.csdn.net/peihang1354092549/article/details/41957369
          如果您看不懂中文,请尝试使用翻译软件阅读。

          他为旧版本提供了这个代码:

          public void JSONArray_remove(int index, JSONArray JSONArrayObject) throws Exception{
              if(index < 0)
                  return;
              Field valuesField=JSONArray.class.getDeclaredField("values");
              valuesField.setAccessible(true);
              List<Object> values=(List<Object>)valuesField.get(JSONArrayObject);
              if(index >= values.size())
                  return;
              values.remove(index);
          }
          

          【讨论】:

            【解决方案7】:

            在我的情况下,我想删除状态为非零值的 jsonobject,所以我做了一个函数“removeJsonObject”,它采用旧 json 并提供所需的 json,并在构造函数中调用该函数。

            public CommonAdapter(Context context, JSONObject json, String type) {
                    this.context=context;
                    this.json= removeJsonObject(json);
                    this.type=type;
                    Log.d("CA:", "type:"+type);
            
                }
            
            public JSONObject removeJsonObject(JSONObject jo){
                    JSONArray ja= null;
                    JSONArray jsonArray= new JSONArray();
                    JSONObject jsonObject1=new JSONObject();
            
                    try {
                        ja = jo.getJSONArray("data");
            
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    for(int i=0; i<ja.length(); i++){
                        try {
            
                            if(Integer.parseInt(ja.getJSONObject(i).getString("status"))==0)
                            {
                                jsonArray.put(ja.getJSONObject(i));
                                Log.d("jsonarray:", jsonArray.toString());
                            }
            
            
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    try {
                        jsonObject1.put("data",jsonArray);
                        Log.d("jsonobject1:", jsonObject1.toString());
            
                        return jsonObject1;
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    return json;
                }
            

            【讨论】:

              【解决方案8】:

              要从 android 的 Listview 中删除某些元素,它将删除您的特定元素并将其绑定到 listview。

              BookinhHistory_adapter.this.productPojoList.remove(position);
              
              BookinhHistory_adapter.this.notifyDataSetChanged();
              

              【讨论】:

                【解决方案9】:
                We can use iterator to filter out the array entries instead of creating a new  Array. 
                
                'public static void removeNullsFrom(JSONArray array) throws JSONException {
                                if (array != null) {
                                    Iterator<Object> iterator = array.iterator();
                                    while (iterator.hasNext()) {
                                        Object o = iterator.next();
                                        if (o == null || o == JSONObject.NULL) {
                                            iterator.remove();
                                        }
                                    }
                                }
                            }'
                

                【讨论】:

                • 欢迎来到 StackOverflow!请务必在您的答案中添加解释,以帮助其他人理解
                • 希望它能解决问题,但请添加对代码的解释,以便用户完全理解他/她真正想要的。
                【解决方案10】:
                static JSONArray removeFromJsonArray(JSONArray jsonArray, int removeIndex){
                    JSONArray _return = new JSONArray();
                    for (int i = 0; i <jsonArray.length(); i++) {
                        if (i != removeIndex){
                            try {
                                _return.put(jsonArray.getJSONObject(i));
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    return _return;
                }
                

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 2012-02-03
                  • 2021-05-27
                  • 2017-01-15
                  • 2016-11-06
                  • 2011-01-27
                  相关资源
                  最近更新 更多