【问题标题】:Deserialize json array in Dart/Flutter在 Dart/Flutter 中反序列化 json 数组
【发布时间】:2020-01-02 20:09:51
【问题描述】:

如何反序列化这个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}");

【问题讨论】:

    标签: arrays json flutter dart


    【解决方案1】:
    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" }, ]
    【解决方案2】:

    你可以尝试使用这条线,

    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”访问该值;

    【讨论】:

      【解决方案3】:

      我也遇到了同样的问题,但我用下面的代码解决了。

      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,然后将对象插入到模型中

      【讨论】:

        猜你喜欢
        • 2021-09-05
        • 2021-08-31
        • 2020-08-24
        • 2018-12-18
        相关资源
        最近更新 更多