Rup*_*dav 29 java arrays android json
我正在构建一个应用程序,我从服务器请求一个PHP文件.此PHP文件返回一个JSONArray,其中包含JSONObjects作为其元素,例如,
[
{
"uniqid":"h5Wtd",
"name":"Test_1",
"address":"tst",
"email":"ru_tst@tst.cc",
"mobile":"12345",
"city":"ind"
},
{...},
{...},
...
]
Run Code Online (Sandbox Code Playgroud)
我的代码:
/* 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();
}
}
Run Code Online (Sandbox Code Playgroud)
如何从此JSONArray中删除特定元素?
Vin*_*raj 41
试试这个代码
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);
Run Code Online (Sandbox Code Playgroud)
编辑:
使用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));
}
}
}
Run Code Online (Sandbox Code Playgroud)
Sub*_*ian 18
如果有人为Android平台返回相同的问题,remove()如果您的目标是Android API-18或更低版本,则无法使用内置方法.该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.
}
}
Run Code Online (Sandbox Code Playgroud)
编辑 丹尼尔指出,静默处理错误是一种糟糕的风格.代码改进了.