如果在groovy中未获得键/值,如何设置默认值

jvidinwx  于 2022-09-21  发布在  其他
关注(0)|答案(1)|浏览(198)

在读取JSON数组并Map值时,我有一个要求:

输入:

[
{
    "Name": "1",
    "Partner": "11"
},
{
    "Name": "2"
},
{
    "Name": "3",
    "Partner": "33"
} 
]

正如我们所看到的,在第二个对象中没有“Partner”键,那么现在我需要如下设置默认值:

[
{
    "Name": "1",
    "Partner": "11"
},
{
    "Name": "2",
    "Partner": 0
},
{
    "Name": "3",
    "Partner": "33"
}
]
wh6knrhe

wh6knrhe1#

您可以这样做:

String jsonInputString = """
    [{"Name": "1", "Partner": "11" },
     {"Name": "2"},
     {"Name": "3", "Partner": "33" } ]
"""

// parse the JSON into a List of Map
def maps = new JsonSlurper().parseText(jsonInputString)

def resultingMaps = maps.collect { map ->
    if(!map.containsKey('Partner')) {
        // the numbers in the initial map are Strings but
        // the question shows this one as a number, so here
        // it is a number, could just as well be a String with
        // the 0 in it...
        map.Partner = 0
    }
    map
}

// resultingMaps will be [[Name:1, Partner:11], [Name:2, Partner:0], [Name:3, Partner:33]]

编辑:

我刚接触Groovy,不确定如何继续,尝试了几个使用“WithDefault”的东西,但没有成功

withDefault可能不是您想要的,因为除非请求该密钥,否则它不会将0放入Map。你可以通过运行这个..。

def resultingMaps = maps.collect { map ->
    map.withDefault { key ->
        if(key == 'Partner') {
            return 0
        }
    }
}

// this will makes sure every Map has a "Partner" entry...
resultingMaps*.get('Partner')

// resultingMaps will be [[Name:1, Partner:11], [Name:2, Partner:0], [Name:3, Partner:33]]

相关问题