2
JSONArray jsonArray = new JSONArray();

jsonArray.put(1);
jsonArray.put("empty");
jsonArray.put(2);
jsonArray.put(3);
jsonArray.put("empty");
jsonArray.put(4);
jsonArray.put("empty");

lets say we have this jsonArray, there are strings empty, how to remove them without leaving gaps?

user3112115
  • 695
  • 3
  • 12
  • 23

5 Answers5

2

You can use the following code :

for (int i = 0, len = jsonArray.length(); i < len; i++) {
    JSONObject obj = jsonArray.getJSONObject(i);
    String val = jsonArray.getJSONObject(i).getString();
    if (val.equals("empty")) {            
        jsonArray.remove(i);
    }
}
Gastón Saillén
  • 12,319
  • 5
  • 67
  • 77
Sujith PS
  • 4,776
  • 3
  • 34
  • 61
0

You can use this following code

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 string equal to "empty"
        if (!"empty".equals(jsonArray.getString(i)) 
        {
            list.put(jsonArray.get(i));
        }
   } 
 //Now, list JSONArray has no empty string values
}
Keerthivasan
  • 12,760
  • 2
  • 32
  • 53
0

take a look at this post. Make a list to put the indexes of the elements with the "empty" string and iterate over your list (the one with the "empty" elements) saving the indexes of the items to delete. After that, iterate over the previosly saved indexes and use

list.remove(position);

where position takes the value of every item to delente (within the list of index).

Community
  • 1
  • 1
MRodriguez08
  • 189
  • 1
  • 7
0

Should work with few fixes to Keerthi's code:

for (int i = 0; i < jsonArray.length(); i++) {
    if (jsonArray.get(i).equals("empty")) {
        jsonArray.remove(i);
    }
}
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
michali
  • 401
  • 2
  • 11
0

you can use string replace after converting the array to string as,

 JSONArray jsonArray = new JSONArray();
 jsonArray.put(1);
 jsonArray.put("empty");
 jsonArray.put(2);
 jsonArray.put(3);
 jsonArray.put("empty");
 jsonArray.put(4);
 jsonArray.put("empty");
 System.err.println(jsonArray);
 String jsonString = jsonArray.toString();
 String replacedString = jsonString.replaceAll("\"empty\",", "").replaceAll("\"empty\"", "");
 jsonArray = new JSONArray(replacedString);
 System.out.println(jsonArray);

Before replace:

jsonArray is [1,"empty",2,3,"empty",4,"empty"]

After replace:

jsonArray is [1,2,3,4]
AJJ
  • 3,570
  • 7
  • 43
  • 76