我想通过其余的Web服务获取城市列表:
Future<List<City>> fetchCities() async {
final response =
await http.get('https://my-url/city',
headers: {HttpHeaders.acceptHeader: "application/json"});
if (response.statusCode == 200) {
// If the call to the server was successful, parse the JSON
return compute(parseCities, response.body);
} else {
// If that call was not successful, throw an error.
throw Exception('Failed to load cities');
}
}
然后解析:
List<City> parseCities(String responseBody) {
final parsed = json.decode(responseBody)['data']['children'].cast<Map<String, dynamic>>();
return parsed.map<City>((json) => City.fromJson(json['data'])).toList();
}
这是City
类的定义:
class City {
final String id;
final String name;
City({this.id, this.name});
factory City.fromJson(Map<String, dynamic> json) {
return City(
id: json['id'],
name: json['name'],
);
}
}
我的示例responseBody
是:
[{\"id\":\"599\",\"name\":\"Bia\u0142ystok-dev\",\"location\":{\"long\":\"23.15\",\"lat\":\"53.13\"}}]
(目前,我想省略location
,仅获取ID和名称)。我的json.decode
抛出异常:
类型'String'不是'索引'的类型'int'的子类型
该如何解决?有什么想法吗?
答案 0 :(得分:2)
您发布的json字符串不包含键data
或children
,因此要解析该json,您需要将parse方法更改为以下内容:
List<City> parseCities(String responseBody) {
final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<City>((json) => City.fromJson(json)).toList();
}
尽管我认为使用List.from
代替.cast
final parsed = List<Map<String, dynamic>>.from(json.decode(responseBody));