0

I have gone through various articles but didn't find any simple way to sort the API response in ascending or descending order using groovy. Can someone please help on this?

import groovy.json.JsonSlurper

def inputJson = '''{
   "status" : "success",
   "locale" : "",
   "data" : {
      "periods" : [
         {
            "payCycleId" : "custompayperiod",
            "sequence" : 1,
            "cycleStartDate" : "2018-10-01",
            "cycleEndDate" : "2018-10-08"
         },
         {
            "payCycleId" : "custompayperiod",
            "sequence" : 2,
            "cycleStartDate" : "2018-10-09",
            "cycleEndDate" : "2018-10-16"
         }
      ]
   }
}

Want to sort above response based on sequence.

syed naveed
  • 85
  • 2
  • 12

1 Answers1

0

There are a lot of ways. For example:

def json = new JsonSlurper().parseText(inputJson)
//Descending
json.data.periods = json.data.periods.toSorted { a, b -> b.sequence <=> a.sequence }
//Ascending
//json.data.periods = json.data.periods.toSorted { a, b -> a.sequence <=> b.sequence }
String output = JsonOutput.prettyPrint(JsonOutput.toJson(json))
Evgeny Smirnov
  • 2,886
  • 1
  • 12
  • 22