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

时间:2019-05-24 15:45:43

标签: json 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}"  }

2 个答案:

答案 0 :(得分:0)

该代码有几处错误:  1.遍历没有“数据”节点的节点。使用parsed.data  2.每个节点都是类似地图的结构。因此,您需要检查地图是否包含值为prodType的键ULTRA。使用it.prodType == 'ULTRA'

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

答案 1 :(得分:0)

我能够弄清楚

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