arraysjsongroovyjsonbuilder

Groovy method to add new Object to List is not working properly


I have a Groovy code to manipulate an Array of JSON objects.

My input is like the following (name: accounts):

[ { "F57UI02A_AID": "00206847" }, { "F57UI02A_AID": "00206855" }, { "F57UI02A_AID": "00206852" } ]

And I need to manipulate it to add to each internal JSON a sequence number. The expected output is:

[ { "F57UI02A_AID ": "00206847", "Sequence ": "1"
}, { "F57UI02A_AID": "00206855", "Sequence ": "2" }, { "F57UI02A_AID ": "00206852", "Sequence ": "3" } ]

In my code, I'm collecting all F57UI02A elements to get the number's list. Then, I iterate over each JSON element, in order to create a new single one, having both F57UI02A element and the sequence number that I want to assign.

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;

When I run a test, I obtain the following output, instead the expected one:

[{"F57UI02A_AID":"00206852","Sequence":"3"}, {"F57UI02A_AID":"00206852","Sequence":"3"}, {"F57UI02A_AID":"00206852","Sequence":"3"}]

Do you know why I'm getting three instances of the last JSON element, instead of having the correct number/sequence in the output?


Solution

  • Sounds like you fixed your issue, but here is an idea on how to do this leveraging more features of 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 ) )