首页 > 解决方案 > 使用 Groovy 从 Json 对象数组中获取 Json 对象

问题描述

我想为下面的 Json 数组获取 prodType ULTRA 的 productLines。我得到了地图数组并使用 findIndexValues 来获取索引,但它不起作用。我错过了什么?我查看了结构不太复杂的类似示例,并且与我正在尝试的示例没有太大区别

这是我的数据:

   def static modelData="""
{



  "models": [
    {

        "transactionId": "01-PROD0021",
        "prodCode": "ISN-2017WDE",
        "product": "VASCULAR DNNT",
        "prodType": "SDISCNT",
        "productLines": [

     {
                "productLineId": "ELECT-2221",
                "productDescriptor": "XTRA-SONIC DNNP",
                "unitPrice": "",
            },
            {
                "productLineId": "ELECT-2223",
                "productDescriptor": "HEADPH",
                "unitPrice": "1.33",
            }
        ]
    },


   {
        "transactionId": "01-PROD0024",
        "prodCode": "ISN-5543XDR",
        "product": "ULTRASOUND DEEP SONAR",
        "prodType": "ULTRA",
        "productLines": [
            {
                "productLineId": "MEDCN-XTR221",
                "productDescriptor": "ELECTRONIC RESPR",
                 "unitPrice": "2.44",
            },
            {
                "productLineId": "MEDCN-XTR376",
                "productDescriptor": "SPNG ELECTRONIC DEFIB",
                "unitPrice": "6.22",
            }
         }  
        ]
]
     }
"""

这是我的尝试:

  def parsed = new JsonSlurper().parseText(modelData)

      // Find index of the prodCode with 'ULTRA'

         int [] vals=parsed.data.findIndexValues{

        it -> it.key=='prodType' &&  it.value=='ULTRA'}

        //Does not print anything

       vals?.each {println "Found an index! ${it}"  }

标签: jsongroovy

解决方案


代码有几处错误: 1. 循环通过一个“数据”节点,而该节点没有。使用parsed.data 2. 每个节点都是一个类似地图的结构。因此,您检查地图是否包含prodType具有 value的键ULTRA。使用it.prodType == 'ULTRA'.

专业提示: 1. 您可以打印闭包上的数据,以便您更快地找到解决方案。


推荐阅读