[java] How do I remove a specific element from a JSONArray?

I am building one app in which I request a PHP file from server. This PHP file returns a JSONArray having JSONObjects as its elements e.g.,

[ 
  {
    "uniqid":"h5Wtd", 
    "name":"Test_1", 
    "address":"tst", 
    "email":"[email protected]", 
    "mobile":"12345",
    "city":"ind"
  },
  {...},
  {...},
  ...
]

my code:

/* 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();
  }
}

How do I remove a specific element from this JSONArray?

This question is related to java android arrays json

The answer is


Try this code

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);

Edit: Using ArrayList will add "\" to the key and values. So, use JSONArray itself

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));
        }
   } 
}

 JSONArray jArray = new JSONArray();

    jArray.remove(position); // For remove JSONArrayElement

Note :- If remove() isn't there in JSONArray then...

API 19 from Android (4.4) actually allows this method.

Call requires API level 19 (current min is 16): org.json.JSONArray#remove

Right Click on Project Go to Properties

Select Android from left site option

And select Project Build Target greater then API 19

Hope it helps you.


We can use iterator to filter out the array entries instead of creating a new  Array. 

'public static void removeNullsFrom(JSONArray array) throws JSONException {
                if (array != null) {
                    Iterator<Object> iterator = array.iterator();
                    while (iterator.hasNext()) {
                        Object o = iterator.next();
                        if (o == null || o == JSONObject.NULL) {
                            iterator.remove();
                        }
                    }
                }
            }'

In case if someone returns with the same question for Android platform, you cannot use the inbuilt remove() method if you are targeting for Android API-18 or less. The remove() method is added on API level 19. Thus, the best possible thing to do is to extend the JSONArray to create a compatible override for the remove() method.

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.
     }
}

EDIT As Daniel pointed out, handling an error silently is bad style. Code improved.


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;

}

i guess you are using Me version, i suggest to add this block of function manually, in your code (JSONArray.java) :

public Object remove(int index) {
    Object o = this.opt(index);
    this.myArrayList.removeElementAt(index);
    return o;
}

In java version they use ArrayList, in ME Version they use Vector.


To Remove some element from Listview in android then it will remove your specific element and Bind it to listview.

BookinhHistory_adapter.this.productPojoList.remove(position);

BookinhHistory_adapter.this.notifyDataSetChanged();

You can use reflection

A Chinese website provides a relevant solution: http://blog.csdn.net/peihang1354092549/article/details/41957369
If you don't understand Chinese, please try to read it with the translation software.

He provides this code for the old version:

public void JSONArray_remove(int index, JSONArray JSONArrayObject) throws Exception{
    if(index < 0)
        return;
    Field valuesField=JSONArray.class.getDeclaredField("values");
    valuesField.setAccessible(true);
    List<Object> values=(List<Object>)valuesField.get(JSONArrayObject);
    if(index >= values.size())
        return;
    values.remove(index);
}

In my case I wanted to remove jsonobject with status as non zero value, so what I did is made a function "removeJsonObject" which takes old json and gives required json and called that function inside the constuctor.

public CommonAdapter(Context context, JSONObject json, String type) {
        this.context=context;
        this.json= removeJsonObject(json);
        this.type=type;
        Log.d("CA:", "type:"+type);

    }

public JSONObject removeJsonObject(JSONObject jo){
        JSONArray ja= null;
        JSONArray jsonArray= new JSONArray();
        JSONObject jsonObject1=new JSONObject();

        try {
            ja = jo.getJSONArray("data");

        } catch (JSONException e) {
            e.printStackTrace();
        }
        for(int i=0; i<ja.length(); i++){
            try {

                if(Integer.parseInt(ja.getJSONObject(i).getString("status"))==0)
                {
                    jsonArray.put(ja.getJSONObject(i));
                    Log.d("jsonarray:", jsonArray.toString());
                }


            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        try {
            jsonObject1.put("data",jsonArray);
            Log.d("jsonobject1:", jsonObject1.toString());

            return jsonObject1;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return json;
    }

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?