我想通过这种方式从 rest 网络服务中获取城市列表:
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
抛出异常:
type 'String' is not a subtype of type 'int' of 'index'
如何解决?有什么想法吗?
最佳答案
您发布的 json 字符串不包含键 data
或 children
因此要解析该 json,您需要将解析方法更改为以下内容:
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));
关于android - Flutter - 无法解析 json 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54515833/