簡體   English   中英

如何在 dart 中對與 JSON 之間的自定義對象列表進行編碼和解碼?

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

我有一個甜甜圈 class 有自己的屬性,我創建了一個甜甜圈對象列表,我想在 JSON 中對其進行編碼和解碼。 我怎樣才能做到這一點? 我已經實現了對對象本身的解析,但是在嘗試對這些對象的列表執行相同操作時遇到了麻煩。

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

您必須解碼數組:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM