groovy

how to read each value from JSON array in Groovy


I am new to Groovy and trying to read each value from a JSON array. logic I wanted to achieve through the loop.

Input JSON

{
    "AUnit": "EA",
    "Quantity": 2,
      
    "SerialNumbers": [
        {
            "SNumber": "IR-240607000100"
        },
        {
            "SNumber": "IR-240607000101"
        }
    ]
}
   
**Groovy Code which I tried with loop :**

     def Message processData(Message message) {
            //Get message and parse to json
            
            def json = message.getBody(java.io.Reader) 
            def data = new JsonSlurper().parse(json)
        
            data.SerialNumbers.each { element ->
                    // Get SerialNumber
                    def sourceValue_Number="${record.text()}"
               def builder_AddSrlNmbr = new JsonBuilder();
                builder_AddSrlNmbr
                {
                    'SerialNumber'  sourceValue_SerialNumber
                    
                
                } 
    }
        return message
     }

logic I wanted to achieve through the loop.

Output expected

{
            "SNumber": "IR-240607000100"
  }
            
{
            "SNumber": "IR-240607000101"
 }

Thank you Sateesh


Solution

  • So getting it working without all the Message/body stuff you have going on, we can create a String with your example input:

    String body = '''{
        "AUnit": "EA",
        "Quantity": 2,
          
        "SerialNumbers": [
            {
                "SNumber": "IR-240607000100"
            },
            {
                "SNumber": "IR-240607000101"
            }
        ]
    }'''
    

    We can then parse this json into a variable

    import groovy.json.*
    
    def json = new JsonSlurper().parseText(body)
    

    And then for each entry in the SerialNumbers list, we can create a new object containing the value with the required key:

    def newBody = json.SerialNumbers.collect {
        [SerialNumber: it.SNumber]
    }
    

    And then use JsonBuilder to change this back into a pretty string

    String result = new JsonBuilder(newBody).toPrettyString()
    

    If we print result out, we can see it's the required result:

    [
        {
            "SerialNumber": "IR-240607000100"
        },
        {
            "SerialNumber": "IR-240607000101"
        }
    ]