Java - 在没有POJO的情况下以递归方式从JSON字符串中删除字段 [英] Java - Remove Fields from a JSON String recursively without POJOs
问题描述
如何从递归的JSON字符串中删除具有指定名称的某些字段?
例如,我想从以下JSON中删除字段secondName :
INPUT:
{
name :abc,
secondName:qwe,
add:abcd,
moreDetails:{
secondName:qwe,
年龄:099
}
}
输出:
{
name:abc,
add:abcd ,
moreDetails:{
age:099
}
}
我必须从许多具有不同结构/模式的不同JSON中删除一些字段,因此我将无法对POJO进行反序列化/序列化。
如果你知道架构和层次结构,你可以这样做:
JsonObject jsonObj = gson.fromJson(json,JsonObject.class);
jsonObj.getAsJsonObject(moreDetails)。remove(secondName);
System.out.println(jsonObj.getAsString());
请参阅此内容以获取更多信息从JsonObject内的Json中删除键
否则你需要编写一个动态函数来检查JSON对象的每个元素并尝试在其中找到 secondName
元素并将其删除。 / p>
所以在这里考虑你有多个嵌套对象然后你需要编写一个函数,它将遍历每个元素并检查它的类型,如果它再次jsonObject以递归方式调用相同的方法或者反复检查当前元素,在每次检查时你还需要验证密钥,如果它与必须删除的密钥匹配,那么你可以删除它并继续它。
有关如何检查JSON值类型的提示,请参阅如何检查JSONObject中值的类型?
How do I remove some fields with a specified name from a JSON string recursively ?
For example, I want to remove the field "secondName" from the following JSON:
INPUT:
{
"name" : "abc",
"secondName": "qwe",
"add" : "abcd",
"moreDetails" : {
"secondName": "qwe",
"age" : "099"
}
}
OUTPUT:
{
"name" : "abc",
"add" : "abcd",
"moreDetails" : {
"age" : "099"
}
}
I have to remove some fields from a lot of different JSONs with different structures/schema, so I won't be able to deserialize/serialize to/from a POJO.
You can do like below if you know the schema and heirarchy:
JsonObject jsonObj= gson.fromJson(json, JsonObject.class);
jsonObj.getAsJsonObject("moreDetails").remove("secondName");
System.out.println(jsonObj.getAsString());
refer this for more info Remove key from a Json inside a JsonObject
else you need to write a dynamic function which will check each and every element of JSON object and try to find the secondName
element in it and remove it.
So consider here as you have multiple nested objects then you need to write a function which will iterate over each element and check its type if its again a jsonObject call the same method recursively or iteratively to check against current element, in each check you need to also verify that the key, if it matches with the key which has to be removed then you can remove it and continue the same.
for a hint on how to check a value type of JSON see this How to check the type of a value from a JSONObject?
这篇关于Java - 在没有POJO的情况下以递归方式从JSON字符串中删除字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!