【发布时间】:2019-06-28 04:12:36
【问题描述】:
我想通过这种方式从 REST 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 和 name)。我的json.decode 抛出异常:
类型'String'不是'index'类型'int'的子类型
如何解决这个问题?有什么想法吗?
【问题讨论】: