Pablo Garcia
Pablo Garcia

Reputation: 381

Sort JSON Array from JSON Objects in Android?

I have the next JSON response:

[{
    format: "jpeg",
    id: 001,
    author: "Mery Rose"
},
{
    format: "jpeg",
    id:002,
    author: "Alex Turner"

}

With this Get call, I obtain by ID order: 001, 002

@GET("/list")
Call<ArrayList<Groups>> imageList();

I need to sort by an author to obtain first Alex an then Mery.

A little help pls.

Upvotes: 0

Views: 482

Answers (3)

user2340612
user2340612

Reputation: 10733

As an alternative to @NJ's answer, you could use new Java 8 Comparator.comparing factory, where you can provide a function that extracts the values to be used when comparing objects.

Collections.sort(imageList, Comparator.comparing(Groups::getAuthor));

Upvotes: 0

N J
N J

Reputation: 27535

I don't think Retrofit is providing in-build sort on response directly.

For sorting response you have to do it manually using comparator like below

Collections.sort(imageList, new Comparator<Groups>() {
    @Override
    public int compare(Groups g1, Person g2) {
        return g1.getAuthor().compareTo(g2.getAuthor());
    }
});

Upvotes: 2

Sasi Kumar
Sasi Kumar

Reputation: 13358

Use Collections like this

Collections.sort(imageList, new Comparator<Groups>() {
public int compare(Groups G1, Groups G2) {
    return G1.getAuthor().compareTo(G2.getAuthor());
}
});

Upvotes: 1

Related Questions