user3112115
user3112115

Reputation: 715

Java how to remove strings from JSONArray

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?

Upvotes: 2

Views: 3855

Answers (5)

Sujith PS
Sujith PS

Reputation: 4864

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

Upvotes: 2

AJJ
AJJ

Reputation: 3628

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]

Upvotes: 0

Keerthivasan
Keerthivasan

Reputation: 12880

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
}

Upvotes: 0

michali
michali

Reputation: 431

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

Upvotes: 0

MRodriguez08
MRodriguez08

Reputation: 191

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

Upvotes: 0

Related Questions