2013-12-19 35 views
1
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"); 

去除串让说我们有这个jsonArray,有串empty,怎么不留空隙删除它们?的Java如何从JSONArray

+0

JSONArray从哪个API中使用? –

+0

iam使用此导入org.json.JSONArray; – user3112115

+0

已经有链接解决方案http://stackoverflow.com/questions/18497162/how-to-remove-element-from-json-array –

回答

1

您可以使用下面的代码:

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

您可以使用此下面的代码

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 
} 
0

看看this post。 制作一个列表,将元素的索引放入“空”字符串中,并迭代您的列表(具有“空”元素的列表),以保存要删除的项目的索引。在此之后,遍历previosly保存索引和使用

list.remove(position); 

其中位置需要每一个项目的价值delente(索引列表内)。

0

应该有一些修正工作,以Keerthi代码:

for (int i = 0; i < jsonArray.length(); i++) { 
    if (jsonArray.get(i).equals("empty")) { 
     jsonArray.remove(i); 
    } 
} 
+0

请注意,使用getString()的版本将不起作用,因为第一个元素不是字符串... – michali

0

你可以使用字符串数组转换为字符串作为取代后,

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

之前更换:

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

替换后:

jsonArray is [1,2,3,4]