我有一个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元素的三个示例,而不是在输出中有正确的数字/序列吗?
2条答案
按热度按时间cdmah0mi1#
听起来你已经解决了你的问题,但是这里有一个关于如何利用Groovy的更多功能来做到这一点的想法:
toiithl62#
我想补充一下前面的答案,因为我们可以使用一些更好的东西:
产生与接受的答案中的代码相同的输出。