Luis
Luis

Reputation: 545

Remove JsonObeject Before Android api lvl 19

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

Answers (3)

Kevin Coppock
Kevin Coppock

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

hasan
hasan

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

Blackbelt
Blackbelt

Reputation: 157457

before api level 19, the trick was to parse the object in a Collection, remove the item that you don't need and then create a new JSONArray with the constructor that takes a collection. Here the documentation

Upvotes: 0

Related Questions