具有此json文件:
{
"rolesToAdd": [],
"rolesToModify": [
{
"name": "administrator",
"nativeRole": "AdminUser",
"description": "Administrator role",
"permissions": [
{
"operation": "CanAcceptRequest",
"name": "Can admin accept request",
"value": false
},
{
"operation": "CanSeeRequest",
"name": "Can admin see request",
"value": false
}
]
},
{
"name": "simpleUser",
"nativeRole": "User",
"description": "User role",
"permissions": [
{
"operation": "CanPostRequest",
"name": "Can user post request",
"value": false
},
{
"operation": "CanCancel",
"name": "Can user cancel request",
"value": false
}
]
}
]
}
我需要更改此json中的值。我写了这样的方法:
Map configMap = ReadAboveJson()
def setAdminCanSeeRequest(boolean canSee) {
configMap.rolesToModify[0].permissions[1].value = canSee
}
def setUserCanPostRequest(boolean canPost) {
configMap.rolesToModify[1].permissions[0].value = canPost
}
如何编写这些方法,以便它们可以通过键“ name”等于“ administrator”来在rolesToModify列表中查找元素的索引,然后能够通过键“ operation”相等来在权限列表中查找索引到“ CanSeeRequest”?
我试图做这样的事情:
int rolesToModifyIndex = configMap.rolesToModify.findIndexOf { object -> object.name == "administrator"}
但是它不起作用。感谢您的帮助。
答案 0 :(得分:0)
检查ReadAboveJson
方法的代码,可能存在一些问题,因为findIndexOf
的工作方式如您所述:
import groovy.json.JsonSlurper
def input = '''{
"rolesToAdd": [],
"rolesToModify": [
{
"name": "administrator",
"nativeRole": "AdminUser",
"description": "Administrator role",
"permissions": [
{
"operation": "CanAcceptRequest",
"name": "Can admin accept request",
"value": false
},
{
"operation": "CanSeeRequest",
"name": "Can admin see request",
"value": false
}
]
},
{
"name": "simpleUser",
"nativeRole": "User",
"description": "User role",
"permissions": [
{
"operation": "CanPostRequest",
"name": "Can user post request",
"value": false
},
{
"operation": "CanCancel",
"name": "Can user cancel request",
"value": false
}
]
}
]
}
'''
def json = new JsonSlurper().parseText(input)
assert json.rolesToModify.findIndexOf { it.name == 'simpleUser' } == 1
assert json.rolesToModify.findIndexOf { it.name == 'administrator' } == 0
不过,您可以对find
方法使用更简单的方法,该方法可以返回给定名称的角色,例如:
def user = json.rolesToModify.find { it.name == 'simpleUser' }
assert user.name == 'simpleUser'
assert user.permissions[0].value == false
答案 1 :(得分:0)
请注意,JSON无效。假设进行了简单的更正,并且像这样的设置器:
def setAdminCanSeeRequest = { def configMap, def canSee ->
myFind(configMap)["value"] = canSee
configMap
}
然后可以将问题指定为以下内容:
def configMap = new groovy.json.JsonSlurper().parseText(s)
assert ! myFind(configMap)["value"]
configMap = setAdminCanSeeRequest(configMap, true)
assert myFind(configMap)["value"]
myFind
的实现是:
def myFind = { def configMap ->
configMap.rolesToModify.find {
it['name'] == 'administrator'
}['permissions'].find {
it['operation'] = 'CanSeeRequest'
}
}
直接根据需要向myFind
添加参数。