【问题标题】:How to remove empty json object in jsonarray如何删除jsonarray中的空json对象
【发布时间】:2017-05-18 21:21:47
【问题描述】:
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
    }]

【问题讨论】:

  • 考虑为您的问题添加更多详细信息

标签: java arrays json


【解决方案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);
       }
   } 
}

然后只需使用 list 代替 jsonArray

【讨论】:

    【解决方案2】:

    试试这个方法

       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>
    

    【讨论】:

      猜你喜欢
      • 2013-11-19
      • 2023-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多