在Dart/Flutter中反序列化JSON数组

6

如何反序列化此JSON数组[{"i":737,"n":1}]以获取变量"i"和"n"。

反序列化类

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

我正在尝试使用这段代码反序列化对象,但当没有数组时使用它,但是使用数组时我不知道该怎么办。

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

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

你可以将JSON解析为列表,这样就可以在数组中使用fromJson。

如果所有的 JSON 数据都具有相同的名称,例如:[ { "store": "AMAZON" }, { "store": "FLIPKART" }, { "store": "WALMART" }, { "store": "ALIBABA" } ] - Ferdinand
PortasAbertas中的fromJson方法来自哪里? - 68060

5
你可以尝试使用这几行代码,
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"]);

对于列表中的每个值,您都有一个JSON,并且可以使用"i"或"n"访问该值;


0
你可以将它转换成一个 List<dynamic>,并将该列表映射到你所期望的模型的 fromJson 方法。
final decoded = jsonDecode(json) as List<dynamic>;
final output = decoded
    .map((e) => ItemCategoryModel.fromJson(
        e as Map<String, dynamic>))
    .toList();

0
我也遇到了同样的问题,但是我使用以下代码解决了它。
List jsonResult = jsonDecode(await RequestApiCallDemo().loadAsset());
for (var value in jsonResult) {
      ItemCategoryModel itemCategoryModel = ItemCategoryModel.fromJson(value);
      print("itemCategoryModel Item = " + itemCategoryModel.title);
}

如果我们将json转换为dart,我们只会得到支持Json-Object的模型,因此更好的方法是先进行jsonDecode,然后将对象插入到您的模型中。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接