【问题标题】:Flutter - unable to parse json arrayFlutter - 无法解析 json 数组
【发布时间】: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'的子类型

如何解决这个问题?有什么想法吗?

【问题讨论】:

    标签: android json dart flutter


    【解决方案1】:

    您发布的 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));
    

    【讨论】:

      猜你喜欢
      • 2020-06-26
      • 2020-07-24
      • 1970-01-01
      • 1970-01-01
      • 2020-07-13
      • 1970-01-01
      • 2021-07-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多