40

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":"ru_tst@tst.cc", 
    "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?

Laurel
  • 5,771
  • 12
  • 29
  • 54
Rupesh Yadav
  • 15,096
  • 5
  • 54
  • 71

10 Answers10

48

Try this code

ArrayList<String> list = new ArrayList<String>();     
JSONArray jsonArray = (JSONArray)jsonObject; 

if (jsonArray != null) { 
   int len = jsonArray.length();
   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));
        }
   } 
}
Vinothkumar Arputharaj
  • 4,459
  • 4
  • 26
  • 36
  • 1
    if (jsonArray != null) makes no sense in your edit sample, because it will never be null. And even if it would, the line before it would throw a NullPointerException. This is also the case in the original sample. – hounce Dec 15 '20 at 10:21
20

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.

C--
  • 16,124
  • 6
  • 53
  • 59
  • 1
    This is bad coding style. In case of an error, the element is not removed, but the invoking code has no chance to know this. a better way is to _not_ use try..catch but using `throws JSONException` in the function header – Daniel Alder Feb 14 '14 at 12:08
  • 1
    @DanielAlder The `remove` method can't throw an Exception because the overridden method doesn't do so. – C-- Feb 14 '14 at 12:43
  • 1
    Ok, in this case I would put a `throw new RuntimeException(e)` (or `InternalError`) instead of `e.printStackTrace();return this;` - just for case – Daniel Alder Feb 15 '14 at 20:37
  • It is not recommended to extend the default class. Better to create the `remove()` method in the class where you are using it. – Stack Overflow Nov 29 '19 at 23:09
4
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;

}
Fabio Guerra
  • 724
  • 6
  • 13
3
 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.

Mansukh Ahir
  • 3,833
  • 5
  • 38
  • 61
2

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.

HappyBoyz
  • 29
  • 1
1

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

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

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();
Mickael B.
  • 4,186
  • 3
  • 20
  • 39
Rakesh Jha
  • 51
  • 3
0
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();
                        }
                    }
                }
            }'
  • Welcome to StackOverflow! Please make sure to add an explain to your answer to help others understand it – Markus May 28 '20 at 11:47
  • Hope It will solve issue but please add explanation of your code with it so user will get perfect understanding which he/she really wants. – Jaimil Patel May 28 '20 at 11:54
0
static JSONArray removeFromJsonArray(JSONArray jsonArray, int removeIndex){
    JSONArray _return = new JSONArray();
    for (int i = 0; i <jsonArray.length(); i++) {
        if (i != removeIndex){
            try {
                _return.put(jsonArray.getJSONObject(i));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
    return _return;
}