Reputation: 13
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,
}]
}
Upvotes: 1
Views: 654
Reputation: 42184
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, e.g.
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]]]
Upvotes: 1