扑 - 无法解析JSON阵列

问题描述 投票:0回答:1

我想获取来自其他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\"}}]

(现在,我想ommit location,只取ID和名称)。我json.decode抛出异常:

类型“字符串”不是“索引”的类型“INT”的子类型

如何解决呢?有任何想法吗?

android json dart flutter
1个回答
2
投票

你已经发布的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();
}

虽然我认为这是使用qazxsw好的做法POI代替qazxsw POI

List.from
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.