Reputation: 181
I have Dynamic JSON String i want to remove the last JSON object from the JSONARRAY in android. here is my dynamic JSON String in android. My json string is
("{\"findAllUsersResponse\": "+arguments[0].toString()+"}");
{
"findAllUsersResponse": [
{
"id": "kicJw2whXyuGjbNo936L",
"name": "Fghhjj",
"udid": "2AA120E3-7478-4AD4-9C68-9C0920669B84"
},
{
"id": "NEF45TWNI6-Uc_r7938R",
"name": "ssss",
"udid": "1DD083C2-7F1D-4BB3-9AB9-691A5FD251CC"
},
{
"id": "xuXY7Ah2-O-jL4Zk939D",
"name": "Test",
"udid": "A892E0AB-6732-4F42-BEFA-3157315E9EE4"
},
{
"id": "w1FnBz8B9ciWUzBk939k",
"name": "Aditi",
"udid": "A892E0AB-6732-4F42-BEFA-3157315E9EE4"
}
]
}
Upvotes: 1
Views: 2678
Reputation: 220
If your String is not going to change and you only want last object to be deleted use substring and create new string.
String finduserjson= "{\"findAllUsersResponse\": "+arguments[0].toString()+"}");
String t = finduserjson.substring(finduserjson.indexOf("{"), finduserjson.lastIndexOf(",{"));
String j = "]}";
finduserjson = t+j;
Cheers
Upvotes: 1
Reputation: 341
Was facing a similar problem. There are no methods in the JSONarray object to get what you want. You could make a function to remove it. Saw this solution somewhere.
public static JSONArray remove(final int index, final JSONArray from) {
final List<JSONObject> objs = getList(from);
objs.remove(index);
final JSONArray jarray = new JSONArray();
for (final JSONObject obj : objs) {
jarray.put(obj);
}
return jarray;
}
public static List<JSONObject> getList(final JSONArray jarray) {
final int len = jarray.length();
final ArrayList<JSONObject> result = new ArrayList<JSONObject>(len);
for (int i = 0; i < len; i++) {
final JSONObject obj = jarray.optJSONObject(i);
if (obj != null) {
result.add(obj);
}
}
return result;
}
Cheers!
Upvotes: 1
Reputation: 1926
If you are using JSON
rather than GSON
or JACKSON
, then you cannot call .remove()
method because you would not find it there.
Best thing you can do is, re-create a new JSONArray
and add required JSONObjects
in it.
Upvotes: 0