如何从 JSON 字符串中递归删除某些具有指定名称的字段?
例如,我想从以下 JSON 中删除“secondName”字段:
输入:
{
"name" : "abc",
"secondName": "qwe",
"add" : "abcd",
"moreDetails" : {
"secondName": "qwe",
"age" : "099"
}
}
输出:
{
"name" : "abc",
"add" : "abcd",
"moreDetails" : {
"age" : "099"
}
}
我必须从具有不同结构/模式的许多不同 JSON 中删除一些字段,因此我将无法对 POJO 进行反序列化/序列化。
最佳答案
Gson 将任何有效的 Json 反序列化为 LinkedTreeMap
,例如:
LinkedTreeMap<?,?> ltm = new Gson().fromJson(YOUR_JSON, LinkedTreeMap.class);
然后就是使用一些递归方法来进行清理:
public void alterEntry(Entry<?, ?> e) {
if(e.getValue() instanceof Map) {
alterMap((Map<?, ?>) e.getValue());
} else {
if(e.getKey().equals("secondName")) { // hard coded but you see the point
e.setValue(null); // we could remove the whole entry from the map
// but it makes thing more complicated. Setting null
// achieves the same.
}
}
}
public void alterMap(Map<?,?> map) {
map.entrySet().forEach(this::alterEntry);
}
用法:
alterMap(ltm);
关于Java - 在没有 POJO 的情况下递归地从 JSON 字符串中删除字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53225341/