本文介绍了在Groovy中使用JSONBuilder排除空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以使用默认的JsonBuilder库在Groovy中创建JSON值,以排除对象的所有空值?例如Jackson在Java中通过注释类以排除空值的方式.
Is it possible to create JSON values in Groovy using the default JsonBuilder library to exclude all the null values of an object? Such as what Jackson does in Java by annotating classes to exclude null values.
一个例子是:
{
"userId": "25",
"givenName": "John",
"familyName": null,
"created": 1360080426303
}
应打印为:
{
"userId": "25",
"givenName": "John",
"created": 1360080426303
}
推荐答案
由于我的方法在具有List
属性的Map
上工作,因此不确定是否适合您:
Not sure if it's OK for you as my method works on a Map
with List
properties:
def map = [a:"a",b:"b",c:null,d:["a1","b1","c1",null,[d1:"d1",d2:null]]]
def denull(obj) {
if(obj instanceof Map) {
obj.collectEntries {k, v ->
if(v) [(k): denull(v)] else [:]
}
} else if(obj instanceof List) {
obj.collect { denull(it) }.findAll { it != null }
} else {
obj
}
}
println map
println denull(map)
产量:
[a:a, b:b, c:null, d:[a1, b1, c1, null, [d1:d1, d2:null]]]
[a:a, b:b, d:[a1, b1, c1, [d1:d1]]]
过滤掉null
的值之后,您可以将Map
呈现为JSON.
After filter null
values out, you then can render the Map
as JSON.
这篇关于在Groovy中使用JSONBuilder排除空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!