Как удалить определенный элемент из JSONArray?

Я создаю одно приложение, в котором я запрашиваю файл PHP с сервера. Этот PHP файл возвращает JSONArray с JSONObjects как его элементы, например,

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

мой код:

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

Как удалить определенный элемент из этого JSONArray?

Ответы

Ответ 1

Попробуйте этот код

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: Использование ArrayList добавит "\" к ключу и значениям. Итак, используйте JSONArray

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

Ответ 2

Если кто-то вернется с тем же вопросом для платформы Android, вы не сможете использовать встроенный метод remove(), если вы настроите таргетинг на Android API-18 или меньше. Метод remove() добавляется на уровне API 19. Таким образом, самое лучшее, что можно сделать, это расширить JSONArray, чтобы создать совместимое переопределение для метода remove().

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

ИЗМЕНИТЬ Как заметил Даниил, обращение с ошибкой - это плохой стиль. Улучшен код.

Ответ 3

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;

}

Ответ 4

 JSONArray jArray = new JSONArray();

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

Примечание: - Если remove() не существует в JSONArray, тогда...

API 19 из Android (4.4) фактически разрешает этот метод.

Для вызова требуется уровень API 19 (текущий мин - 16): org.json.JSONArray # remove

Щелкните правой кнопкой мыши в проекте Перейти к свойствам

Выберите Android с левой страницы.

И выберите Project Build Target больше, чем API 19

Надеюсь, это поможет вам.

Ответ 5

Я предполагаю, что вы используете версию Me, я предлагаю добавить этот блок функции вручную в ваш код (JSONArray.java):

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

В java-версии они используют ArrayList, в версии ME они используют Vector.

Ответ 6

В моем случае я хотел удалить jsonobject со статусом как ненулевое значение, поэтому я сделал функцию "removeJsonObject", которая принимает старый json и дает требуемый json и вызывает эту функцию внутри 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;
    }

Ответ 7

Вы можете использовать отражение

На китайском веб-сайте представлено соответствующее решение: http://blog.csdn.net/peihang1354092549/article/details/41957369
Если вы не понимаете китайский язык, попробуйте прочитать его с помощью программного обеспечения для перевода.

Он предоставляет этот код для старой версии:

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