android - Flutter - 无法解析 json 数组

标签 android json dart flutter

我想通过这种方式从 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 字符串不包含键 datachildren 因此要解析该 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/

相关文章:

Android Studio 电容器 Cordova 插件错误

Javascript:具有多个查询参数的嵌套 JSON api 请求

dart - Flutter 突然无法将 apk 安装到真机

android - 如何使用地理围栏避免 Android 中的多个回调级别

android - Android开发有没有类似于WPF数据绑定(bind)的概念?

android - fragment 未附加到导航组件的上下文

Android Retrofit 2 自定义 JSON 请求

java - 在 Jackson Mixins 中同时使用 @JsonIgnore 和 @JsonProperty 时出现问题

android - flutter 等效于 `View::onAttachedToWindow` 和 `View::onDetachedFromWindow`

flutter - 在 Flutter 中裁剪视频