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?
-
JSONArray from which API you are using ?Sujith PS– Sujith PS2013年12月19日 12:34:54 +00:00Commented Dec 19, 2013 at 12:34
-
iam using this import org.json.JSONArray;user3112115– user31121152013年12月19日 12:36:23 +00:00Commented Dec 19, 2013 at 12:36
-
already we have link with solution stackoverflow.com/questions/18497162/…Karthikeyan Sukkoor– Karthikeyan Sukkoor2013年12月19日 12:38:42 +00:00Commented Dec 19, 2013 at 12:38
-
@KarthikeyanSukkoor the link you pointed out is for javascript. The question is on Java and was tagged in java. There is no splice() in JsonArray in java.AJJ– AJJ2013年12月19日 13:11:04 +00:00Commented Dec 19, 2013 at 13:11
5 Answers 5
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);
}
}
Comments
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).
Comments
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);
}
}
1 Comment
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
}
Comments
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]