Groovy向List添加新对象的方法无法正常工作

7xzttuei  于 12个月前  发布在  其他
关注(0)|答案(2)|浏览(104)

我有一个Groovy代码来操作JSON对象数组。
我的输入如下(名称:账户):
[ {“F57UI02A_AID”:“00206847”},{“F57UI02A_AID”:“00206855”},{“F57UI02A_AID”:[00206852]
我需要操作它来为每个内部JSON添加一个序列号。预期输出为:
[ {“F57UI02A_AID“:“00206847”,“序列“:“1个”
},{“F57UI02A_AID”:“00206855”,“序列“:“2”},{“F57UI02A_AID“:“00206852”,“序列“:“3”}
在我的代码中,我收集所有F57 UI 02 A元素以获得数字列表。然后,我遍历每个JSON元素,以创建一个新的JSON元素,其中包含F57 UI 02 A元素和我想要分配的序列号。

def accountList = accounts.collect{ it.get("F57UI02A_AID") };
    
   int size = accounts.size();
   def currentElement = new JsonBuilder();
   String sequence = "";
   def outputArray = [];
    
   for (int i = 0; i < size; i++){
       sequence = i+1;
       currentElement F57UI02A_AID: accountList[i], Sequence: sequence;
       outputArray[i] = currentElement;
       //outputArray << currentElement;
   }
   
   returnMap.put("output", outputArray);
   return returnMap;

当我运行一个测试时,我获得了以下输出,而不是预期的输出:
[{“F57UI02A_AID”:“00206852”,“序列”:“3”},{“F57UI02A_AID”:“00206852”,“序列”:“3”},{“F57UI02A_AID”:“00206852”,“序列”:“3”}]
你知道为什么我得到了最后一个JSON元素的三个示例,而不是在输出中有正确的数字/序列吗?

cdmah0mi

cdmah0mi1#

听起来你已经解决了你的问题,但是这里有一个关于如何利用Groovy的更多功能来做到这一点的想法:

import groovy.json.*

String input = """[ 
   { "F57UI02A_AID": "00206847" }, 
   { "F57UI02A_AID": "00206855" }, 
   { "F57UI02A_AID": "00206852" } ]
"""
List<Map> json = new JsonSlurper().with { it.parseText( input ) }
List<Map> output = json
   .findAll { it["F57UI02A_AID"] }
   .withIndex()
   .collect { 
      def (Map current, int seq) = it
      current.Sequence = seq + 1
      current
   }
println( JsonOutput.toJson( output ) )
toiithl6

toiithl62#

我想补充一下前面的答案,因为我们可以使用一些更好的东西:

import groovy.json.*

String input = '''[ { "F57UI02A_AID": "00206847" }, 
                    { "F57UI02A_AID": "00206855" }, 
                    { "F57UI02A_AID": "00206852" } ]'''

def json = new JsonSlurper().parseText( input ) 
def output = json.findAll { it["F57UI02A_AID"] }
                 .indexed(1)
                 .collect { i, m -> m + [Sequence: i] }
println( JsonOutput.toJson( output ) )

产生与接受的答案中的代码相同的输出。

相关问题