如何在jsonarray中删除空的json对象

时间:2017-01-04 14:31:09

标签: java arrays json

JSONObject sss = arr_cat_details_old.getJSONObject(0).getJSONArray("pac_selected").getJSONObject(1);
         sss.remove("pack_selected_id");

"pac_selected": [{
        "pack_selected_id": "7"
    }, {}, {
        "pack_selected_id": 45
    }]

2 个答案:

答案 0 :(得分:1)

假设:

String jsonString = "pac_selected": [{
    "pack_selected_id": "7"
}, {}, {
    "pack_selected_id": 45
}]

我会根据this answer执行以下操作:

JSONArray list = new JSONArray();     
JSONArray jsonArray = new JSONArray(jsonstring); 
int len = jsonArray.length();

if (jsonArray != null) { 
   for (int i=0;i<len;i++)
   { 
       String element = jsonArray.get(i);

       if (!element.isEmpty()) 
       {
          list.put(element);
       }
   } 
}

然后只使用列表而不是 jsonArray

答案 1 :(得分:0)

尝试此方法

   String json = .... // your json

   Type type = new TypeToken<Map<String, Object>>() {}.getType();
   Map<String, Object> data = new Gson().fromJson(json, type);

   for (Iterator<Map.Entry<String, Object>> it = data.entrySet().iterator(); it.hasNext();) {
            Map.Entry<String, Object> entry = it.next();
            if (entry.getValue() == null) {
                it.remove();
            } else if (entry.getValue().getClass().equals(ArrayList.class)) {
                if (((ArrayList<?>) entry.getValue()).size() == 0) {
                    it.remove();
                }
            }
        }

    String json1 = new GsonBuilder().setPrettyPrinting().create().toJson(data);
    System.out.println("Latest json "+json1);

将此添加到pom.xml

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.2</version>
</dependency>