尝试将数据从 json 解析到 Map
DartError:类型错误:“JSArray”的实例:类型“List”不是类型“List”的子类型
最终我需要“数据”作为地图
这是最简单的代码:
final jsonData = await rootBundle.loadString('assets/data/dataTest.json');
final data = json.decode(jsonData);
final modules = data['modules'];
final steps = modules['data'];
print(steps);
final List<double> keys =
steps.keys.map((e) => double.parse(e)).toList();
json 示例:
{
"modules": {
"name": "name1",
"data": {
"1": "450",
"2": "26.8",
"4": "12.4",
"3.07": "14",
"1.25": "79",
"1.53": "47.5",
"2.5": "18.8",
"1.86": "30.2",
"1.66": "43.2"
}
}
}
您可以使用
Map.map()
将 Map<String, dynamic>
转换为 Map<double, double>
,如下所示:
final steps = modules['data'] as Map<String, dynamic>; // let the compiler know what type of map it already is
final result = steps.map<double, double>(
(k, v) => MapEntry(double.parse(k), double.parse(v)));
print(result.runtimeType); // Map<double, double>