简体   繁体   中英

how to decode complex json in dart/flutter?

After my request to server i get this json:

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

i want to decode them and show them on my screen

so my class model is:

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

now i have decoded this json like this:

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

i can access to id, name, description but i can't use src in image array, and it doesn't load on my screen.

is there any solution?

change

bodybytedecoded["image"]["src"]

to

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

try with this

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

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

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

//just print data to console

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

//you got 56043,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM