Reputation: 545
Hello i have one json
String prev_string= [
{
"mac_address": "D3-D3-D3-D3-D4",
"minor": "2333",
"time": "11-12-2014 2:36 PM",
"major": "4444"
},
{
"mac_address": "D3-D3-D3-D3-D3",
"minor": "45555",
"time": "11-12-2014 2:36 PM",
"major": "2322"
}
]
JSONArray json= new JSONArray(prev_string);
json.remove(1);
Im need remove the second object, json.remove(1) work fine, but in android before lvl 19 dont work .remove, How do I can make it work?
Regards!
Upvotes: 2
Views: 1385
Reputation: 134684
Yeah, sort of surprising that it wasn't added until API 19. You could just define a utility method some where that iterates over the source object, and adds all elements to the new object (except for the specified index). Something like this:
public static JSONArray removeJsonObjectAtJsonArrayIndex(JSONArray source, int index) throws JSONException {
if (index < 0 || index > source.length() - 1) {
throw new IndexOutOfBoundsException();
}
final JSONArray copy = new JSONArray();
for (int i = 0, count = source.length(); i < count; i++) {
if (i != index) copy.put(source.get(i));
}
return copy;
}
Upvotes: 4
Reputation: 24185
You are right it is a method added starting from api 19. There is no easy workaround here.
Two solutions:
Use another library to hold the Json objects.
OR
Create a new Json array and add objects to it one by one except the one you want to delete.
Upvotes: 1