简体   繁体   中英

How to fetch a data from JSON in flutter?

I have a JSON file and i want to fetch the data. here a small Json example, in this Example as we see the employee has 2 properties, name and List of countries:

{
  "Employee": [
    { 
      "id":1
      "name": "John",
      "Countries": [
        { 
          "id" :1
          "country": "Uk"
        },
        {
          "id" :2
          "country": "USA"
        },
        {
          "id" :3
          "country": "Germany"
        }
      ]
    }
  ]
}

I used to use this method to fetch the data from JSON but the problem i faced is that this method works just with Json that doesnt have a list property:

Future<List<EmployeeModel>> fetchEmployeeList() async {
  try {
    final response = await http.get(Uri.parse(url));
    if (response.statusCode == 200) {
      var data = jsonDecode(response.body) as List;
      print(data);
      final employeeList = data.map((e) => EmployeeModel.fromJson(e)).toList();
      return employeeList;
    } else {
      throw Exception("Failed to load ");
    }
  } catch (e) {
    print(e);
    rethrow;
  }
}

here the model file:

import 'dart:convert';

List<EmployeeModel> employeeModelFromJson(String str) =>
    List<EmployeeModel>.from(
        json.decode(str).map((x) => EmployeeModel.fromJson(x)));

String employeeModelToJson(List<EmployeeModel> data) =>
    json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class EmployeeModel {
  EmployeeModel({
    this.id,
    this.name,
    this.countries,
  });

  int id;
  String name;
  List<Country> countries;

  factory EmployeeModel.fromJson(Map<String, dynamic> json) => EmployeeModel(
        id: json["id"],
        name: json["name"],
        countries: List<Country>.from(
            json["Countries"].map((x) => Country.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "name": name,
        "Countries": List<dynamic>.from(countries.map((x) => x.toJson())),
      };
}

class Country {
  Country({
    this.id,
    this.country,
  });

  int id;
  String country;

  factory Country.fromJson(Map<String, dynamic> json) => Country(
        id: json["id"],
        country: json["country"],
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "country": country,
      };
}
var data = jsonDecode(response.body);
print(data['Employee'][0]['Countries'][0]['country'];
//Output uk

Also consider creating a model for the json so you can parse it easily and don't have to write named keys.

https://docs.flutter.dev/development/data-and-backend/json

There are some online tools like quicktype.io too

EDIT

final employeeList = data.map((e) => EmployeeModel.fromJson(e)).toList();
  print(employeeList[0].countries [0].country);
//Output uk

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM