【问题标题】:how to decode complex json in dart/flutter?如何在 dart/flutter 中解码复杂的 json?
【发布时间】:2021-12-28 12:06:07
【问题描述】:

在我向服务器发出请求后,我得到了这个 json:

[
    {
        "id": 56012,
        "name": "The name",
        "description": "<p>description</p>\n",
        "regular_price": "45000",
        "sale_price": "45000",
        "tags": [],
        "images": [
            {
                "id": 56043,
                "src": "pic link",
            }
        ],
    },
]

我想将它们解码并显示在我的屏幕上

所以我的班级模型是:

class ProductModel {
  late int _id;
  late String _name;
  late String _regular_price;
  late String _description;
  late var _image;

  ProductModel(this._id, this._name, this._regular_price, this._description,
      this._image);

  get image => _image;

  set image(value) {
    _image = value;
  }

  String get regular_price => _regular_price;

  set regular_price(String value) {
    _regular_price = value;
  }

  String get description => _description;

  set description(String value) {
    _description = value;
  }

  String get name => _name;

  set name(String value) {
    _name = value;
  }

  int get id => _id;

  set id(int value) {
    _id = value;
  }
}

现在我已经像这样解码了这个 json:

var bodybytedecoded= jsonDecode(utf8.decode(response.bodyBytes));
 var productItem = ProductModel(bodybytedecoded["id"], bodybytedecoded["name"], bodybytedecoded["regular_price"],bodybytedecoded["description"],bodybytedecoded["image"]["src"]);

我可以访问 id、name、description,但我不能在图像数组中使用 src,并且它不会加载到我的屏幕上。

有什么解决办法吗?

【问题讨论】:

    标签: android json flutter api dart


    【解决方案1】:

    bodybytedecoded["image"][0]["id"] //for id

    bodybytedecoded["image"][0]["src"] // 用于 src

    //只是打印数据到控制台

    print("${bodybytedecoded["image"][0]["id"]}"); 
    

    //你得到了 56043,

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    【解决方案2】:

    试试这个

    bodybytedecoded["image"][0]["src"] // here you change the index of image 
    

    【讨论】:

      【解决方案3】:

      改变

      bodybytedecoded["image"]["src"]
      

      bodybytedecoded["images"][0]["src"]
      

      【讨论】:

        猜你喜欢
        • 2019-03-13
        • 2021-12-28
        • 2020-12-21
        • 2019-05-26
        • 2020-04-13
        • 2020-10-29
        • 2021-06-20
        相关资源
        最近更新 更多