Deserialize json array in Dart/Flutter

How to deserialize this json array [{"i":737,"n":1}] to get the variable "i" e "n".

Class to deserialize

    class PortasAbertas {
  int i;
  int n;

  PortasAbertas({this.i, this.n});

  PortasAbertas.fromJson(Map<String, dynamic> json) {
    i = json['i'];
    n = json['n'];
  }

  Map<String, dynamic> toJson() {
    return {
      'i': i,
      'n': n
    };
  }
}

I'm trying deserialize the object using this code, but use it when dont have a array, but using array i don't know i can do it

   PortasAbertas objeto = new PortasAbertas.fromJson(responseJson);
     String _msg = ("Portas abertas: ${objeto.n}");

Upvotes: 6

Views: 17742

Answers (4)

Matthiee
Matthiee

Reputation: 493

You can convert it to a List<dynamic> and map that list to fromJson of the model you expect.

final decoded = jsonDecode(json) as List<dynamic>;
final output = decoded
    .map((e) => ItemCategoryModel.fromJson(
        e as Map<String, dynamic>))
    .toList();

Upvotes: 0

sharma_kunal
sharma_kunal

Reputation: 2192

I also faced the same issue but I solved using below code.

List jsonResult = jsonDecode(await RequestApiCallDemo().loadAsset());
for (var value in jsonResult) {
      ItemCategoryModel itemCategoryModel = ItemCategoryModel.fromJson(value);
      print("itemCategoryModel Item = " + itemCategoryModel.title);
}

If we convert json to dart we will only get Model that support Json-Object so the better approach is to do jsonDecode first and then insert object to your model

Upvotes: 0

You can try using this lines,

List oo = jsonDecode('[{"i":737,"n":1},{"i":222,"n":111}]');
//here u get the values from the first value on the json array
print(oo[0]["i"]);
print(oo[0]["n"]);

//here u get the values from the second value on the json array
print(oo[1]["i"]);
print(oo[1]["n"]);

and for each value from your list, u have a json and can get access the value using "i" or "n";

Upvotes: 5

Furkan Aydın
Furkan Aydın

Reputation: 193

final List t = json.decode(response.body);
final List<PortasAbertas> portasAbertasList =
     t.map((item) => PortasAbertas.fromJson(item)).toList();
return portasAbertasList;

You can parse your JSON to list like that so you can use fromJson in an array.

Upvotes: 16

Related Questions