首页 > 解决方案 > 使用 Groovy 解析 JSON,其中数组和多个对象没有名称以获取列表

问题描述

groovy 和一般编码的新手。尝试执行以下操作:(我在stackoverflow中查看了许多以前的问答,但我发现的解决方案似乎都不起作用)

我有以下 JSON,我需要从中获取供应商名称的列表/字符串,即输出应该类似于:“供应商 1,供应商 2,供应商 3”

[
   {
       "id":217564,
       "created-at":"2020-01-22T08:59:57+00:00",
       "state":"submitted",
       "supplier":
       {
          "name":"supplier 1"
       }
    },
    {
       "id":217565,
       "created-at":"2020-01-22T09:00:00+00:00",
       "state":"submitted",
       "supplier":
       {
          "name":"supplier 2"
       }
    },
    {
       "id":217566,
       "created-at":"2020-01-22T09:00:48+00:00",
       "state":"submitted",
       "supplier": 
       {
          "name":"supplier 3"
       }
    }
]

我使用以下 groovy 脚本打印出列表中的所有供应商名称:

import groovy.json.*;

@CustomScriptAction(
    input = ['json_response'],
    output = 'suppliers'
)
def CustomScriptAction14()
{
    def object = new JsonSlurper().parseText(json_response.toString())
    def suppliers = "No suppliers"

if(object != null && !object.isEmpty())
{
    for(def i =0; i<object.size();i++)
{
    suppliers = RString.of(object[i].'supplier'.name.toString());

}
}
return suppliers
}

我得到了输出:“供应商 3”

问题是这个脚本只给了我循环中的最后一个供应商,而不是遍历整个循环并打印出所有供应商。所以我尝试了一个不同的脚本:

import groovy.json.*;

@CustomScriptAction(
    input = ['json_response'],
    output = 'suppliers'
)
def CustomScriptAction14()
{
    def object = new JsonSlurper().parseText(json_response)
    def suppliers = object.findAll { it.value instanceof List }
        .values()
        .flatten()
        .collect { [it.'supplier'.'name'] }
}
return suppliers

但有了这个,我得到了一个空白的回应。

我究竟做错了什么?

标签: jsongroovy

解决方案


好吧,这最终起作用了:

import groovy.json.*;

@CustomScriptAction(
    input = ['json_response'],
    output = 'suppliers'
)


def customScript()
{

def jsonSlurper = new JsonSlurper()
def object = jsonSlurper.parseText(json_response.toString())
suppliers = RString.of(object.'supplier'.'name'.toString())

}

推荐阅读