简体   繁体   中英

How to encode and decode a list of custom objects to and from JSON in dart?

I have a doughnut class having its own properties, I create a list of doughnut objects and i want to encode and decode that in JSON. How can i achieve that? I have achieved parsing for the objects themselves, but having trouble when trying to do the same for a list of those objects.

import 'package:flutter/material.dart';

class Doughnut {
  String name;
  String filling;
  List<String> toppings;
  double price;
  var days;

  Doughnut(this.name, this.filling, this.toppings, this.price,this.days);

  Doughnut.fromJson(Map<String, dynamic> json) {
    name = json['name'];
    filling = json['filling'];
    var toppingsFromJson = json['toppings'];
    toppings = new List<String>.from(toppingsFromJson);
    price = json['price'];
    var daysFromJson=json["days"];
    days=new Map<String,bool>.from(daysFromJson);
    }

  Map<String, dynamic> toJson() =>
      {"name": name, "filling": filling, 'toppings': toppings, "price": price,"days":days};
}

You have to decode the array:

var toppingsFromJson = jsonDecode(json['toppings']);

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