Deserialize JSON - Dart/Flutter

Asked

Viewed 430 times

0

I have a JSON and want to play it in an array.

final String jsonSample='[{"id":1},{"id":2}]';
var json = jsonDecode(jsonSample);
print (json); //resultado é:  [{id: 1}, {id: 2}]

So far so good, but now I wanted to take only the ID and play it in an array. How can I do?

1 answer

2

Here on this Stackoverflow question I already answered something that solves your question How to compare Map and Json value in flutter?.

I saw that you managed to solve your problem, but it follows another way, you can do it as follows:

Create the class that will receive the data of each object of your JSON

class Conta {
    String nome;
    String email;

    Conta({
      this.nome,
      this.email
    });

    factory Conta.fromJson(Map<String, dynamic> json) => Conta(
        nome: json["nome"],
        email: json["email"]
    );
}

Now turn your own JSON in a List that will receive objects of the type Conta

  String json = '[{"nome":"Marcelo", "email":"[email protected]"}, {"nome":"Caio", "email":"[email protected]"}, {"nome":"Caio", "email":"[email protected]"}]';
  final jsonMap = jsonDecode(json);

  List<Conta> contas;

  contas = (jsonMap as List).map((item) => Conta.fromJson(item)).toList();

With this you will have a list of all existing accounts in your JSON.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.