0
votes

I am currently building an app to read data through a medical api and I am trying to parse the JSON.

I made a model class for the User:

class UserModel {
  String id;
  String nome;
  MedicoModel medico;
  MedicosModel medicos;
  String token;

  String error;

  UserModel(
      {this.id, this.nome, this.token, this.medico, this.medicos, this.error});

  UserModel.fromJson(Map<String, dynamic> json)
      : id = json['login'],
        nome = json['nome'],
        token = json['token'],
        medico = MedicoModel.fromJson(json['medico']),
        medicos = MedicosModel.fromJson(json['medicos']),
        error = '';

  Map<String, dynamic> toJson() => {
        'id': id,
        'nome': nome,
        'token': token,
        'medico': medico.toJson(),
        'medicos': medicos.toJson(),
      };

  UserModel.withError(String errorValue)
      : id = null,
        nome = null,
        token = null,
        medico = null,
        medicos = null,
        error = errorValue;
}

class MedicoModel {
  String crm;
  String nome;

  MedicoModel({this.crm, this.nome});

  MedicoModel.fromJson(Map<String, dynamic> json)
      : crm = json['crm'],
        nome = json['nome'];

  Map<String, dynamic> toJson() => {
        'crm': crm,
        'nome': nome,
      };
}

class MedicosModel {
  List<MedicoModel> medicos;

  MedicosModel({this.medicos});

  MedicosModel.fromJson(Map<String, dynamic> json)
      : medicos = (json['medicos'] as List)
            .map((e) => MedicoModel.fromJson(e))
            .toList();

  Map<String, dynamic> toJson() => {
        'medicos': medicos,
      };
}

This is the JSON information i'm trying to read:

{
  "login": "12345",
  "medico": {
    "crm": "12345",
    "nome": "XXX"
  },
  "medicos": [
    {
      "crm": "12345",
      "nome": "XXX"
    }
  ],
  "token": "5ad0c78d8fc1233b48526e0893cf91c912345706",
  "nome": "XXX"
}

But i am getting the error 'List is not a subtype of type Map<String, dynamic>'. i'm trying to understand how to read json yet, so this is new to me.

How can i fix this error?

1

1 Answers

0
votes

Please take a look at this code, you need to change your code by this way:

 MedicosModel.fromJson(List<dynamic> jsonList)
      : medicos = jsonList['medicos']
            .map((e) => MedicoModel.fromJson(e))
            .toList();