繁体   English   中英

使用Groovy从Json对象数组中获取Json对象

[英]Get the Json object from a array of Json objects using Groovy

我想为下面的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}"  }

代码有几个问题:1。循环通过“数据”节点,没有。 使用parsed.data 2.每个节点都是类似地图的结构。 因此,检查映射是否包含值为ULTRA的键prodType 使用it.prodType == 'ULTRA'

专业提示:1。您可以在闭包上打印数据,以便您更快地获得解决方案。

我弄清楚了

def parsed = new JsonSlurper().parseText(modelData)
def vals = parsed.models.find{ it.prodType == 'ULTRA' }?.productLines

暂无
暂无

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

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