简体   繁体   English

Groovy:根据object从JSON中检索一个值

[英]Groovy: Retrieve a value from a JSON based on an object

So I have a JSON that looks like this所以我有一个 JSON 看起来像这样

{
   "_embedded" : {
      "userTaskDtoList" : [
         {
            "userTaskId" : 8,
            "userTaskDefinitionId" : "JJG",
            "userRoleId" : 8,
            "workflowId" : 9,
            "criticality" : "MEDIUM",
            **"dueDate"** : "2021-09-29T09:04:37Z",
            "dueDateFormatted" : "Tomorrow 09:04",
            "acknowledge" : false,
            "key" : 8,
         },
         {
            "userTaskId" : 10,
            "userTaskDefinitionId" : "JJP",
            "userRoleId" : 8,
            "workflowId" : 11,
            "criticality" : "MEDIUM",
            **"dueDate"** : "2021-09-29T09:06:44Z",
            "dueDateFormatted" : "Tomorrow 09:06",
            "acknowledge" : false,
            "key" : 10,
         },
         {
            "userTaskId" : 12,
            "userTaskDefinitionId" : "JJD",
            "userRoleId" : 8,
            "workflowId" : 13,
            "criticality" : "MEDIUM",
            **"dueDate"** : "2021-09-29T09:59:07Z",
            "dueDateFormatted" : "Tomorrow 09:59",
            "acknowledge" : false,
            "key" : 12,
         }
      ]
   }
}

It's a response from a REST request.这是来自 REST 请求的响应。 What I need is to extract the data of key "dueDate" ONLY from a specific object and make some validations with it.我需要的是仅从特定的 object 中提取键“dueDate”的数据并对其进行一些验证。 I'm trying to use Groovy to resolve this.我正在尝试使用 Groovy 来解决这个问题。

The only thing I've managed to do is this:我唯一能做的就是:

import groovy.json.*

def response = context.expand( '${user tasks#Response}' )
def data = new JsonSlurper().parseText(response)

idValue = data._embedded.userTaskDtoList.dueDate

Which returns all 3 of the values from the "dueDate" key in the response.它返回响应中“dueDate”键的所有 3 个值。 I was thinking that maybe I can interact with a certain object based on another key, for instance let's say I retrieve only the value from the "dueDate" key, that is part of the object with "userTaskId": 12. How could I do this?我在想,也许我可以根据另一个键与某个 object 进行交互,例如,假设我只从“dueDate”键中检索值,这是带有“userTaskId”的 object 的一部分:12。我该怎么做这?

Any help would be greatly appreciated.任何帮助将不胜感激。

You can find the record of interest, then just grab the dueDate from that您可以find感兴趣的记录,然后从中获取dueDate

data._embedded.userTaskDtoList.find { it.userTaskId == 12 }.dueDate

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM