0

假设我有一个 JSON 请求有效负载,例如

{
    "workflow": {
        "approvalStore": {
            "sessionInfo": {
                "user": "baduser"
            },
            "guardType": "Transaction"
        }
    }
}

我得到了uservia

def user = req.get("workflow").get("approvalStore").get("sessionInfo").get("user")

现在,我得到了一个 RestResponse approvalList,我将其存储为list并返回给调用者 as return approvalList.json as JSON。到目前为止一切顺利。

假设响应 ( approvalList.json) 如下所示 JSONArray -

[
    {
        "objId": "abc2",
        "maker": "baduser"
    },
    {
        "objId": "abc1",
        "maker": "baduser"
    },
    {
        "objId": "abc4",
        "maker": "gooduser"
    }
]

在此处输入图像描述

问题:如何过滤approvalList.json,使其不包含具有的条目(对象)"maker": "baduser"?传递给的值maker本质上应该是user我之前得到的变量。

理想的所需输出 -

在此处输入图像描述

4

2 回答 2

1

如果您总是想要返回单个对象或对象列表,尚不完全清楚,但 usingcollect将是这里的关键:

// given this list
List approvalList  = [
    [objId: "abc2", maker: "baduser"], 
    [objId: "abc1", maker: "baduser"], 
    [objId: "abc4", maker: "gooduser"]
]

// you mentioned you wanted to match a specific user
String user = "baduser"
List filteredList = approvalList.findAll{ it.maker != user}​​​​​​

// wasn't sure if you wanted a single object or a list...
if (filteredList.size() == 1) {
    return filteredList[0] as JSON
} else {
    return filteredList as JSON
}​
于 2020-06-05T01:26:35.357 回答
0

很简单。首先将 JSON 解析成一个对象,然后遍历并测试。

JSONObject json = JSON.parse(text)
json.each(){ it ->
   it.each(){ k,v ->
      if(v=='baduser'){
          // throw exception or something
      } 
   }
}
于 2020-06-04T15:52:21.123 回答