0

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,
      };
}

1 Answer 1

2
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
Sign up to request clarification or add additional context in comments.

3 Comments

oh sorry, i tried to put the Model but got this error "It looks like your post is mostly code; please add some more details." so i had to delete that part. i'll try to edit the question now and see if its working
Oh you can then use model.fromJson(json.decode(response.body));
I added the model file

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.