0

I want to fetch list of cities from rest webservice, this way:

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');
  }
}

Then to parse:

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();
}

And this is City class definition:

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'],
    );
  }
}

My example responseBody is:

[{\"id\":\"599\",\"name\":\"Bia\u0142ystok-dev\",\"location\":{\"long\":\"23.15\",\"lat\":\"53.13\"}}]

(for now, I want to ommit location and only fetch id and name). My json.decode throws exception:

type 'String' is not a subtype of type 'int' of 'index'

How to fix that? Any ideas?

1 Answer 1

2

The json string you have posted does not contain the keys data or children so to parse that json you would need to change your parse method to the following:

List<City> parseCities(String responseBody) {
  final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();

  return parsed.map<City>((json) => City.fromJson(json)).toList();
}

although I think its good practice to use List.from instead of .cast

final parsed = List<Map<String, dynamic>>.from(json.decode(responseBody));
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.