本文介绍了如何删除从JSONArray特定元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am building one app in which I request a PHP file from server. This PHP file returns a JSONArray having JSONObjects as its elements e.g.,

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

我的code:

/* 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删除特定的元素吗?

How do I remove a specific element from this JSONArray?

推荐答案

试试这个code

ArrayList<String> list = new ArrayList<String>();
JSONArray jsonArray = (JSONArray)jsonObject;
int len = jsonArray.length();
if (jsonArray != null) {
   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 本身

Using ArrayList will add "\" to the key and values. So, use JSONArray itself

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));
        }
   }
}

这篇关于如何删除从JSONArray特定元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 02:11