我从服务器得到这样的响应,
[
{
"id":"b2",
"type":"ball"
},
{
"id":"a1",
"type":"apple",
},
{
"id":"d4",
"type":"dog",
},
{
"id":"c3",
"type":"cat",
}
]
但我需要根据“类型”根据字母明智地对上述响应数据进行排序。然后显示列表,我正在使用模型来解析数据。
最佳答案
您要将 JSON 解析成什么数据结构?例如,如果您有一个 Item
类类似于:
class Item {
Item(String id, String type) { ... }
String getType() { ... }
String getId() { ... }
}
然后您将该 JSON 解析为某种 List<Item>
, 那么以下内容应该适用于按类型排序(API 级别 24+),请参阅 Comparator.comparing :
List<Item> items = ...; // however you parse the JSON
Comparator<Item> byType = Comparator.comparing(Item::getType);
Collection.sort(items, byType); // items will now be sorted
对于适用于旧 API 级别的更通用的方法,您可以定义 byType
像这样的比较器:
Comparator<Item> byType = new Comparator<Item> {
public int compare(Item a, Item b) {
return a.getType().compareTo(b.getType());
}
};
关于java - 按字母顺序对从服务器获取的响应进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42795998/