Chingiz
Chingiz

Reputation: 332

deleting value inside JsonArray

I wanna delete the value inside this jsonArray:

{"category_ids":[0,1,2,3,4,5],"keyword":""}

For example, i wanna remove 0 from category_ids jsonArray.

Can anybody help me? Thanks in advance.

Upvotes: 1

Views: 58

Answers (2)

sirmagid
sirmagid

Reputation: 1130

    String load = "{\"category_ids\":[0,1,2,3,4,5],\"keyword\":\"\"}";
    try {

        JSONObject jsonObject_load = new JSONObject(load);
        JSONArray jsonArray =  jsonObject_load.getJSONArray("category_ids");
        Log.d("out", RemoveJSONArray(jsonArray,1).toString());

    } catch (JSONException e) {
        e.printStackTrace();
    }
 public static JSONArray RemoveJSONArray( JSONArray jarray,int pos) {

    JSONArray Njarray = new JSONArray();
    try {
        for (int i = 0; i < jarray.length(); i++) {
            if (i != pos)
                Njarray.put(jarray.get(i));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return Njarray;
 }

Upvotes: 1

Piyush Malaviya
Piyush Malaviya

Reputation: 1091

Below API 19

String result = "{\"category_ids\":[0,1,2,3,4,5],\"keyword\":\"\"}";

        try {
            JSONObject jsonObject = new JSONObject(result);
            JSONArray jsonArray = jsonObject.getJSONArray("category_ids");
            jsonArray = removeValue(jsonArray, 0);  // below api 19
            // jsonArray.remove(0); // above api 19
        } catch (JSONException e) {
            e.printStackTrace();
        }

public JSONArray removeValue(JSONArray jsonArray, int index) {
        JSONArray copyArray = new JSONArray();
        try {
            if (index < jsonArray.length()) {
                for (int i = 0; i < jsonArray.length(); i++) {
                    if (i != index) {
                        copyArray.put(jsonArray.get(i));
                    }
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return copyArray;
    }

Above API 19 use jsonArray.remove(0);

I hope this will help you.

Upvotes: 0

Related Questions