我有一个嵌套对象,例如:
{
"name:"ABC",
"nest1":{
{
"field1": null,
"field2": null,
"field3": [],
"field4": {},
},
"nest2":{
"field1":"123",
"field2":null
}
}
我想清理这个json,并确保输出为:
{
"name:"ABC",
"nest2":{
"field1":"123"
}
}
我写了以下代码:
def withoutNullAndEmptyObj(json: JsValue): JsValue = {
json match {
case JsObject(fields) =>
if (fields.isEmpty) JsNull
else{
fields.foldLeft(new JsObject(Map()))((agg, field) =>
field match{
case (_, JsNull) => agg
case other@(name, value: JsArray) => if (value == emptyArray) agg else agg+other
case (name, value: JsObject) => if (value == emptyObject) agg else agg+(name, withoutNullAndEmptyObj(value))
case other@(name, value) => agg+other
}
)
}
case other => other
}
}
事情是它没有完全发挥作用。 它将产生以下json:
{
"name:"ABC",
"nest1":{},
"nest2":{
"field1":"123"
}
}
这还不够好。
答案 0 :(得分:4)
稍微修改您当前的代码:
def withoutNullAndEmptyObj(json: JsValue): JsValue = {
json match {
case JsObject(fields) =>
if (fields.isEmpty) JsNull
else {
fields.foldLeft(new JsObject(Map()))((agg, field) =>
field match {
case (_, JsNull) => agg
case other @ (name, value: JsArray) => if (value == emptyArray) agg else agg + other
case (name, value: JsObject) => {
if (value == emptyObject) agg
else {
//added further check on else part.
val nested = withoutNullAndEmptyObj(value);
if (nested == emptyObject)
agg
else
agg + (name, nested)
}
}
case other @ (name, value) => agg + other
})
}
case other => other
}
}