Groovy - 如何检查 json 键是否存在
Groovy - How to check if a json key exists
我正在创建一个 REST Mock,它将接收 JSON 请求作为输入:
{
"infoSimIn":{
"idenficationSim":[
{
"imsi":123456789012345
}
]
}
}
如何在返回适当的响应之前检查我的 JSON 是否包含 imsi
密钥?
谢谢你..
这是显示 imsi
是否出现在 json
中的脚本
def str = """
{ "infoSimIn":{
"idenficationSim":[
{
"imsi":123456789012345
}
]
}
}"""
def json = new groovy.json.JsonSlurper().parseText(str)
def result = json.infoSimIn.idenficationSim.collect { it.keySet().contains('imsi')}[0]
assert result == true, 'json does not have imsi'
可以上网快速查询Demo
编辑:基于 OP 评论
更改自:
def str = ...
def json = new groovy.json.JsonSlurper().parseText(str)
到
def json = new groovy.json.JsonSlurper().parseText(mockRequest.requestContent)
编辑:基于 OP 的评论,它成功运行,不像 op 抱怨 null
在 Mock 服务中:
我正在创建一个 REST Mock,它将接收 JSON 请求作为输入:
{
"infoSimIn":{
"idenficationSim":[
{
"imsi":123456789012345
}
]
}
}
如何在返回适当的响应之前检查我的 JSON 是否包含 imsi
密钥?
谢谢你..
这是显示 imsi
是否出现在 json
def str = """
{ "infoSimIn":{
"idenficationSim":[
{
"imsi":123456789012345
}
]
}
}"""
def json = new groovy.json.JsonSlurper().parseText(str)
def result = json.infoSimIn.idenficationSim.collect { it.keySet().contains('imsi')}[0]
assert result == true, 'json does not have imsi'
可以上网快速查询Demo
编辑:基于 OP 评论
更改自:
def str = ...
def json = new groovy.json.JsonSlurper().parseText(str)
到
def json = new groovy.json.JsonSlurper().parseText(mockRequest.requestContent)
编辑:基于 OP 的评论,它成功运行,不像 op 抱怨 null
在 Mock 服务中: