【问题标题】:How to encode and decode a list of custom objects to and from JSON in dart?如何在 dart 中编码和解码自定义对象列表到 JSON 和从 JSON 解码?
【发布时间】:2019-10-04 13:43:22
【问题描述】:

我有一个甜甜圈类,它有自己的属性,我创建了一个甜甜圈对象列表,我想在 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};
}

【问题讨论】:

    标签: json flutter dart


    【解决方案1】:

    你必须解码数组:

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

    【讨论】:

    • 我如何创建一个甜甜圈对象列表,以便在 JSON 中对其进行编码和解码?
    • 当你解码你的响应时,你应该有一个 List > 你可以使用 fromJson 方法将该列表的每个元素映射到 Donut 并传递 Map
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-10
    • 2021-05-13
    • 1970-01-01
    • 2019-06-02
    • 1970-01-01
    • 2012-09-20
    相关资源
    最近更新 更多