简体   繁体   中英

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.

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());
    }
});

Use Collections like this

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

作为@NJ答案的替代方法,您可以使用新的Java 8 Comparator.comparing工厂,您可以在其中提供一个函数,该函数提取比较对象时要使用的值。

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

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