2012-01-11 35 views
16

Tôi đang xây dựng một ứng dụng mà tôi yêu cầu tệp PHP từ máy chủ. file PHP này trả về một JSONArray có JSONObjects như các yếu tố của nó ví dụLàm cách nào để xóa một phần tử cụ thể khỏi JSONArray?

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

mã của tôi:

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

Làm thế nào để loại bỏ một yếu tố cụ thể từ các JSONArray này?

Trả lời

31

Hãy thử mã này

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: Sử dụng ArrayList sẽ thêm "\" để chìa khóa và giá trị. Vì vậy, sử dụng JSONArray tự

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

tôi đoán bạn đang sử dụng phiên bản Me, tôi đề nghị bổ sung khối này chức năng bằng tay, trong mã của bạn (JSONArray.java):

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

Trong phiên bản java họ sử dụng ArrayList, trong phiên bản ME họ sử dụng Vector.

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; 

} 
15

Trong trường hợp nếu một người nào đó trở lại với câu hỏi tương tự cho nền tảng Android, bạn không thể sử dụng inbuilt remove() phương pháp nếu bạn đang nhắm mục tiêu cho Android API-18 hoặc ít hơn. Phương pháp remove() được thêm vào cấp API 19. Vì vậy, điều tốt nhất có thể làm là mở rộng JSONArray để tạo ghi đè tương thích cho phương thức 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. 
    } 
} 

EDIT Như Daniel chỉ ra, xử lý lỗi âm thầm là phong cách xấu. Mã được cải thiện.

+1

Đây là kiểu mã hóa kém. Trong trường hợp lỗi, phần tử không bị xóa, nhưng mã gọi không có cơ hội để biết điều này. một cách tốt hơn là _not_ sử dụng try..catch nhưng sử dụng 'ném JSONException' trong tiêu đề hàm –

+1

@DanielAlder Phương thức' remove' không thể ném ngoại lệ vì phương thức ghi đè không làm như vậy. –

+1

Ok, trong trường hợp này tôi sẽ đặt một 'throw new RuntimeException (e)' (hoặc 'InternalError') thay vì' e.printStackTrace(); trả về giá trị này; '- chỉ dành cho trường hợp –

2
JSONArray jArray = new JSONArray(); 

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

Lưu ý: - Nếuremove() là không có trong JSONArray sau đó ...

API 19 từ Android (4.4) thực sự cho phép phương pháp này.

Gọi đòi hỏi mức API 19 (hiện tại là phút 16): org.json.JSONArray # loại bỏ

Right Click trên Project Đến Thuộc tính

Chọn Android từ tùy chọn trang web trái

Và chọn Target Build Target lớn hơn API 19

Hy vọng nó sẽ giúp bạn.

0

Bạn có thể sử dụng phản ánh

Một trang web của Trung Quốc cung cấp một giải pháp có liên quan: http://blog.csdn.net/peihang1354092549/article/details/41957369
Nếu bạn không hiểu Trung Quốc, hãy cố gắng đọc nó với các phần mềm dịch thuật.

Ông cung cấp mã này cho phiên bản cũ:

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

Trong trường hợp của tôi, tôi muốn loại bỏ JSONObject với tình trạng như giá trị không bằng không, vì vậy những gì tôi đã được thực hiện một chức năng "removeJsonObject" mà mất json cũ và cho json cần thiết và gọi hàm đó bên trong 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; 
    } 
Các vấn đề liên quan