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.,
[
{
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 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;
}
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);
}