我有一个JSON对象,我需要它按键“ SortOrder”的值排序,但是我不确定如何在Dart中执行此操作。
JSON:
"BTS": {
"Id": "2039",,
"SortOrder": "10001",
},
"ETS": {
"Id": "1039",,
"SortOrder": "50",
},
"RTS": {
"Id": "39",,
"SortOrder": "1",
},
"TTS": {
"Id": "139",,
"SortOrder": "1001",
},
通过“ SortOrder”键值对这些对象进行排序的正确方法是什么?
答案 0 :(得分:2)
默认的{}
Dart映射未排序,并且已排序的映射SplayTreeMap
通过键而不是值排序。为了对您的对象列表进行排序,我建议您在本地进行一些转换(如果标签很重要)。
Map<String, <Map<String, String>>> objects = { /* data */ };
List<Map<String, String>> objectList = objects.entries.map((entry) {
return {
'key': entry.key,
// if you don't turn the order back to an int it will order them lexicographically.
'sortOrder:': int.parse(entry.value['sortOrder']),
};
}).toList();
您现在可以使用自定义comparator对列表进行排序。排序方法修改了该列表。
objectList.sort((left, right) {
return left['sortOrder'].compareTo(right['sortOrder']);
});
如果将此列表重新转换为地图,则添加新值后将无法保证它们保持正确的顺序。但是默认情况下,{}
映射(LinkedHashMap
)保留插入顺序。
final Map<String, Map<String, String>> sortedMap = {};
for (var entry in objectList) {
sortedMap[entry['key']] = objects[entry['key']);
}
答案 1 :(得分:1)
乔纳·威廉姆斯方法的简写:
var newMap = Map.fromEntries(originalMap.entries.toList()..sort((e1, e2) =>
int.parse(e1.value["SortOrder"]).compareTo(int.parse(e2.value["SortOrder"]))));
如果效率很重要,最好只将“ SortOrder”字符串解析为整数一次,或者使用对嵌入式数字进行数值比较的字符串比较,例如package:collection中的compareNatural,这是一个好主意。这样,代码将是:
var newMap = Map.fromEntries(originalMap.entries.toList()..sort((e1, e2) =>
compareNatural(e1.value["SortOrder"], e2.value["SortOrder"])));
答案 2 :(得分:0)
import 'package:queries/collections.dart';
void main() {
var query = Dictionary.fromMap(myMap)
.orderBy((kv) => kv.value['SortOrder'] as int)
.toDictionary$1((kv) => kv.key, (kv) => kv.value);
print(query.toMap());
}
var myMap = {
"BTS": {
"Id": "2039",
"SortOrder": 10001,
},
"ETS": {
"Id": "1039",
"SortOrder": 50,
},
"RTS": {
"Id": "39",
"SortOrder": 1,
},
"TTS": {
"Id": "139",
"SortOrder": 1001,
},
};
结果:
{RTS: {Id: 39, SortOrder: 1}, ETS: {Id: 1039, SortOrder: 50}, TTS: {Id: 139, SortOrder: 1001}, BTS: {Id: 2039, SortOrder: 10001}}