0

我有以下代码块,它将创建一个对象,该对象是“basixCertificateNumbers”数组中所有对象的串联字符串。

def object= jsonSlurper.parseText '''
{
    "basixCertificateNumbers": [
        {
          "basixCertificateNumber": "012-012"
        },
        {
            "basixCertificateNumber": "045-123"
          }
      ]
}
'''
def concatdObj = jsonSlurper.parseText '''
{
  "basixNumber" : ""
}
'''

def content = object.each{ entry->
    if(entry.value.getClass().name === "java.util.ArrayList"){
        for (basixIndex = 0 ; basixIndex < entry.value.size(); basixIndex++){
            entry.value[basixIndex].each{ nestedEntry->{
                concatdObj.basixNumber = concatdObj.basixNumber + nestedEntry.value + " "
            }}
        }
        concatdObj.basixNumber = concatdObj.basixNumber.substring(0, concatdObj.basixNumber.length() - 1);
    }}

我目前收到以下错误:

 Ambiguous expression could be either a parameterless closure expression or an isolated open code block;
   solution: Add an explicit closure parameter list, e.g. {it -> ...}, or force it to be treated as an open block by giving it a label, e.g. L:{...} @ line 41, column 56.
   asixIndex].each{ nestedEntry->{
                                 ^

尽管建议的解决方案是在上面贴上标签,但我不确定在哪里贴上它的最佳方式。

当前的解决方案是删除nestedEntry 之后的“{”,如下所示:

entry.value[basixIndex].each{ nestedEntry->
                concatdObj.basixNumber = concatdObj.basixNumber + nestedEntry.value + " "
            }

但是,我相信这不是做事的最佳方式,所以如果有人会有更好的主意。这将是一个很大的帮助!

我希望的输出是:

{
   "basixNumber" : "012-012 045-123"
}
4

1 回答 1

2

你可以做

def content = [
    basixNumber: object.basixCertificateNumbers.basixCertificateNumber.join(' ')
]
String jsonOutput = new JsonOutput().toJson(content)

你不需要concatdObj

于 2021-07-20T10:43:40.547 回答