JSONObject删除空值对

A P*_*der 6 java string format json jsonobject

这是我的Json文件:

{  
   "models":{},
   "path":[  
      {  
         "path":"/web-profiles",
         "operations":[  
            {  
               "type":"",
               "responseMessages":[]
            }
         ]
      }
   ],
   "produces":[]
}
Run Code Online (Sandbox Code Playgroud)

如果键的值为空(包括[],"",{}).如何从Json文件中删除这些对.

  1. 我尝试使用JSONObject内置函数来删除不必要的对.但是,它没有用.
  2. 我尝试使用字符串方法逐行处理它.它有太多的情况,我不能在我的代码中涵盖所有这些情况.(例如,子键'operations',当你想删除所有空值时,这个键(操作)值对也应该被删除.)任何想法?

cod*_*guy 1

首先,您应该json反序列化为Map<String, Object>. 其次,循环映射条目以找出哪个键具有空值或哪个键具有值是实例ArrayList但为空并从 中删除Map。最后,序列化Mapjson.

试试这个代码:

String json = "{'a': 'apple', 'b': 'ball', 'c': 'cat', 'd': null, 'e': []}";
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() instanceof ArrayList) {
        if (((ArrayList<?>) entry.getValue()).isEmpty()) {
            it.remove();
        }
    }
}

json = new GsonBuilder().setPrettyPrinting().create().toJson(data);
System.out.println(json);
Run Code Online (Sandbox Code Playgroud)