如何从 JSONArray 中删除特定元素? [英] How do I remove a specific element from a JSONArray?

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

问题描述

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

<预><代码>[{"uniqid":"h5Wtd","name":"Test_1","地址":"tst","email":"ru_tst@tst.cc","手机":"12345",城市":工业"},{...},{...},...]

我的代码:

/* jArrayFavFans 是我从响应中得到的字符串构建的 JSONArray.它给了我正确的 JSONArray */JSONArray jArrayFavFans=new JSONArray(serverRespons);for (int j = 0; j 

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

解决方案

试试这个代码

ArrayListlist = new ArrayList();JSONArray jsonArray = (JSONArray)jsonObject;如果(jsonArray != null){int len = jsonArray.length();for (int i=0;i

使用 ArrayList 会将 "\" 添加到键和值.所以,使用 JSONArray 本身

JSONArray list = new JSONArray();JSONArray jsonArray = new JSONArray(jsonstring);int len = jsonArray.length();如果(jsonArray != null){for (int i=0;i

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":"ru_tst@tst.cc", 
    "mobile":"12345",
    "city":"ind"
  },
  {...},
  {...},
  ...
]

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

How do I remove a specific element from this JSONArray?

解决方案

Try this code

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

Edit: 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 中删除特定元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆