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文件中删除这些对.
首先,您应该json反序列化为Map<String, Object>. 其次,循环映射条目以找出哪个键具有空值或哪个键具有值是实例ArrayList但为空并从 中删除Map。最后,序列化Map到json.
试试这个代码:
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)
| 归档时间: |
|
| 查看次数: |
14364 次 |
| 最近记录: |