4 回答

TA貢獻1794條經驗 獲得超7個贊
Groovy 已經提供了類和機制來做到這一點,首先你需要導入類groovy.json.JsonGenerator
然后您可以定義要從序列化中忽略的字段:
def generator = new JsonGenerator.Options()
? ? .excludeFieldsByName('id', 'Code')
? ? .build()
最后只需要解析輸出:
String output = generator.toJson(input)
輸出將如下所示:
{
? ? "Status": "Fail",
? ? "Rules": [
? ? ? ? {
? ? ? ? ? ? "Status": "Fail",
? ? ? ? ? ? "Message": "Code error"
? ? ? ? },
? ? ? ? {
? ? ? ? ? ? "Status": "Fail",
? ? ? ? ? ? "Message": "Configuration error"
? ? ? ? }
? ? ]
}
這是我如何做到這一點的完整示例:
import groovy.json.JsonSlurper
import groovy.json.JsonOutput
import groovy.json.JsonGenerator
String json = '''{
? "Status": "Fail",
? "Code": "500",
? "Rules": [{
? ? ? "Status": "Fail",
? ? ? "Message": "Code error",
? ? ? "id": "123456"
? ? },
? ? {
? ? ? "Status": "Fail",
? ? ? "Message": "Configuration error",
? ? ? "id": "12345"
? ? }
? ]
}'''
Map input = new JsonSlurper().parseText(json)
def generator = new JsonGenerator.Options()
? ? .excludeFieldsByName('id', 'Code')
? ? .build()
String output = generator.toJson(input)
println JsonOutput.prettyPrint(output)

TA貢獻1786條經驗 獲得超11個贊
遞歸遍歷 json 并刪除任意深度的特定字段的解決方案:
import groovy.json.*
def str = '''
{
"Status": "Fail",
"Code": "500",
"Rules": [{
"Status": "Fail",
"Message": "Code error",
"id": "123456"
},
{
"Status": "Fail",
"Message": "Configuration error",
"id": "12345"
}
]
}'''
def json = new JsonSlurper().parseText(str)
def clean = recursivelyRemove(json, ['id', 'Code'])
println JsonOutput.prettyPrint(JsonOutput.toJson(clean))
def recursivelyRemove(obj, fieldNames) {
switch(obj) {
case Map:
obj.findAll { k, v ->
!(k in fieldNames)
}.collectEntries { k, v ->
[k, recursivelyRemove(v, fieldNames)]
}
break
case List:
obj.collect { recursivelyRemove(it, fieldNames) }
break
default:
obj
}
}
打?。?/p>
─? groovy solution.groovy 1 ?
{
"Status": "Fail",
"Rules": [
{
"Status": "Fail",
"Message": "Code error"
},
{
"Status": "Fail",
"Message": "Configuration error"
}
]
}
運行時。
這樣做的好處是它不會硬編碼到您的 json 結構中,即如果結構由于某種原因發生變化,此代碼可能仍然有效。
一個潛在的缺點是,如果您的 json 結構非常深(例如數百或數千級嵌套),那么當我們進行遞歸調用時,您可能會收到 StackOverflowException。根據您的情況,這可能會也可能不會。

TA貢獻1853條經驗 獲得超9個贊
var getData = {
"Status": "Fail",
"Code": "500",
"Rules": [{
"Status": "Fail",
"Message": "Code error",
"id": "123456"
},
{
"Status": "Fail",
"Message": "Configuration error",
"id": "12345"
}
]
};
delete getData.Code;
for (var i = 0; i < getData.Rules.length; i++) {
delete getData.Rules[i].id;
}
console.log(getData);
注意:-您可以簡單地使用delete elementValue
來實現這一點

TA貢獻1846條經驗 獲得超7個贊
const obj = {
"Status": "Fail",
"Code": "500",
"Rules": [
{
"Status": "Fail",
"Message": "Code error",
"id": "123456"
},
{
"Status": "Fail",
"Message": "Configuration error",
"id": "12345"
}
]
}
const result = Object.keys(obj).reduce((acc, curr) => {
if (curr !== "Code") {
acc = {
...acc,
[curr]: obj[curr]
}
}
if (curr === "Rules") {
acc = {
...acc,
[curr]: obj[curr].map(rule => {
delete rule.id
return rule
})
}
}
return acc
}, {})
console.log(result)
添加回答
舉報