简体   繁体   中英

Unable to sort object on groovy json

I'm trying to sort certain data (array of classes) based on certain field. However data is not sorted correctly:

FCresJsonParse.sort { a,b -> b.residents.Name<=> a.residents.Name}

Sample JSON looks like this:

{
  "residents" : [
    {
       "linkedin" : null,
        "updated" : "2018-05-31",
       "twitter" : null,
       "organization" : null,
       "title" : null,
       "Name" : "Abc",
       "bio" : null,
    }, {
       "linkedin" : null,
        "updated" : "2018-05-31",
       "twitter" : null,
       "organization" : null,
       "title" : null,
       "Name" : "xyz",
       "bio" : null,
    }]
}

What is the object you are calling .sort {} method on? I assume variable FCresJsonParse is the result returned from

new JsonSlurper().parseText(jsonText)

or something similar. In such case FCresJsonParse is a LazyMap instance, so if you call .sort {} method on it like:

FCresJsonParse.sort { a,b -> b.residents.Name<=> a.residents.Name}

you wont get FCresJsonParse.residents array sorted as expected (in descending order). However, if you call:

FCresJsonParse.residents.sort { a,b -> b.Name<=> a.Name}

it will sort the array in descending order. In this case you can try sorting this array and assigning it back to the field, eg

FCresJsonParse.residents = FCresJsonParse.residents.sort { a,b -> b.Name<=> a.Name}

and then you will get FCresJsonParse similar to:

[residents:[[linkedin:null, updated:2018-05-31, twitter:null, organization:null, title:null, Name:xyz, bio:null], [linkedin:null, updated:2018-05-31, twitter:null, organization:null, title:null, Name:Abc, bio:null]]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM