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?
Đâ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 –
@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. –
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 –