简体   繁体   中英

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?

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

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
}

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

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

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM