我正在构建一个应用程序,在该应用程序中我从服务器请求一个 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 中删除特定元素?
最佳答案
试试这个代码
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));
}
}
}
关于java - 如何从 JSONArray 中删除特定元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8820551/