【问题标题】:How to create a json in dart (Exception Instance of '_CompactLinkedHashSet)如何在 dart 中创建 json('_CompactLinkedHashSet 的异常实例)
【发布时间】:2021-09-25 06:55:45
【问题描述】:

我正在尝试将一些对象转换为 json 以将其发送到 DB,这是我现在拥有的代码:

Map<String, dynamic> bag = {};
    bag = {
      'colors' : [
        for(int i = 0; i < product.colors.length; i ++){

              'id': product.colors[i].id,
              'desc': product.colors[i].desc,
              'sizes': [
                for(int j=0; j < product.colors[i].sizes.length; j ++){
                  product.colors[i].sizes[j].toJson()
                }
              ]
            }]
    };
    print(json.encode(bag));

但我得到的结果是这样的:

将对象转换为可编码对象失败:'_CompactLinkedHashSet>'的实例

我该如何解决?

产品类别:

final String id;
  final String desc;
  final List<Colors> colors;

颜色:

  final String id;
  final String desc;
  final List<Prices> prices;

价格:

  final String id;
  final String desc;
  final List<Types> types;

类型:

  final String id;
  final String desc;
  final List<Sizes> sizes;

尺寸:

  final String id;
  final int stock;
  final String desc;
  final bool filled;
  int quantity;
  final double price;

我想要这样的json:

colors: 
 id : 12
 desc : black
 sizes: [
  id : 0202202
  stock : 10
  desc: Full Size
  filled: true
  quantity : 2
  price : 200
]

【问题讨论】:

  • 你能展示你的product类吗?
  • 更新了问题
  • 你能从product变量中添加样本数据吗?

标签: json flutter dart encode


【解决方案1】:

您创建 JSON 的方式太复杂了。尝试在每个类上添加 toJson() 方法。如果遇到与 JSON 不兼容的对象,Dart JSON 编码器会自动调用此方法。

这是一个例子:

import 'dart:convert';

class Product {
  final String id;
  final String desc;
  final List<Colors> colors;

  Product({
    required this.id,
    required this.desc,
    required this.colors,
  });

  Map<String, Object> toJson() => {
        'id': id,
        'desc': desc,
        'colors': colors,
      };
}

class Colors {
  final int id;
  final String desc;
  final List<Prices> prices;

  Colors({
    required this.id,
    required this.desc,
    required this.prices,
  });

  Map<String, Object> toJson() => {
        'id': id,
        'desc': desc,
        'prices': prices,
      };
}

class Prices {
  final String id;
  final String desc;
  final List<Types> types;

  Prices({
    required this.id,
    required this.desc,
    required this.types,
  });

  Map<String, Object> toJson() => {
        'id': id,
        'desc': desc,
        'types': types,
      };
}

class Types {
  final String id;
  final String desc;
  final List<Sizes> sizes;

  Types({
    required this.id,
    required this.desc,
    required this.sizes,
  });

  Map<String, Object> toJson() => {
        'id': id,
        'desc': desc,
        'sizes': sizes,
      };
}

class Sizes {
  final String id;
  final int stock;
  final String desc;
  final bool filled;
  int quantity;
  final double price;

  Sizes({
    required this.id,
    required this.stock,
    required this.desc,
    required this.filled,
    required this.quantity,
    required this.price,
  });

  Map<String, Object> toJson() => {
        'id': id,
        'stock': stock,
        'desc': desc,
        'filled': filled,
        'quantity': quantity,
        'price': price,
      };
}

void main() {
  final product = Product(id: '1', desc: 'Some text', colors: [
    Colors(id: 1, desc: '', prices: [
      Prices(id: '1', desc: '', types: [
        Types(id: '1', desc: '', sizes: [
          Sizes(
              id: '1',
              stock: 5,
              desc: '',
              filled: true,
              quantity: 2,
              price: 1.0)
        ])
      ])
    ]),
    Colors(id: 2, desc: '', prices: [
      Prices(id: '1', desc: '', types: [
        Types(id: '1', desc: '', sizes: [
          Sizes(
              id: '5',
              stock: 5,
              desc: '',
              filled: true,
              quantity: 2,
              price: 1.0),
          Sizes(
              id: '50',
              stock: 5,
              desc: '',
              filled: true,
              quantity: 2,
              price: 1.0),
        ])
      ])
    ])
  ]);

  final bag = {
    'colors': [
      for (final colors in product.colors)
        {
          'id': colors.id,
          'desc': colors.desc,
          'sizes': [
            for (final prices in colors.prices)
              for (final types in prices.types) ...types.sizes
          ]
        }
    ]
  };

  print(const JsonEncoder.withIndent(' ').convert(bag));
}

输出:

{
 "colors": [
  {
   "id": 1,
   "desc": "",
   "sizes": [
    {
     "id": "1",
     "stock": 5,
     "desc": "",
     "filled": true,
     "quantity": 2,
     "price": 1.0
    }
   ]
  },
  {
   "id": 2,
   "desc": "",
   "sizes": [
    {
     "id": "5",
     "stock": 5,
     "desc": "",
     "filled": true,
     "quantity": 2,
     "price": 1.0
    },
    {
     "id": "50",
     "stock": 5,
     "desc": "",
     "filled": true,
     "quantity": 2,
     "price": 1.0
    }
   ]
  }
 ]
}

这里的一个技巧是,Dart 将调用另一个 toJson() 调用返回的结构内的对象。所以例如Product.toJson 返回一个包含颜色列表的 Map&lt;String, Object&gt;。 Dart 然后在每种颜色上调用toJson(),依此类推。

【讨论】:

  • 问题是我有其他对象,但我只想要这 2 个:我有产品 > 颜色 > 价格 > 类型 > 尺寸。如何使用 toJson 方法仅获取颜色和大小
  • 您只需在 JSON 中使用所需的顶部对象调用 JsonEncoder。使用我的解决方案更容易做到这一点,因为所有对象都将实现 toJson() 方法,因此只需将这些对象中的任何一个直接提供给 JsonEncoder。
  • 我如何挂载'toJson'?我放了一个 var 'sizes'?
  • “mount”是什么意思?
  • 我如何创建它,因为我没有尺寸列表,而是在后面的对象中
【解决方案2】:

这应该对你有帮助,有地图的时候最好转成json,所以你需要把类和它的子类转换成地图,最后转换成json会很简单。

要映射的产品类:

class Product {
final String id;
  final String desc;
  final List<Colors> colors;

  Product(this.id, this.desc, this.colors);
  Map toMap() {
    return {
      'id': this.id,
      'desc': this.desc,
      'colors': this.colors.map((color) => color.toMap()).toList(),
    };
  }
}

要映射的颜色类:

class Colors {

final String id;
  final String desc;
  final List<Sizes> sizes;

  Colors(this.id, this.desc, this.sizes);
  Map toMap() {
    return {
      'id': this.id,
      'desc': this.desc,
      'sizes': this.sizes.map((size) => size.toMap()).toList(),
    };
  }
}

要映射的尺寸类:

class Sizes {
   final String id;
  final int stock;
  final String desc;
  final bool filled;
  int quantity;
  final double price;
  Sizes(this.id, this.stock, this.desc, this.filled, this.quantity, this.price);

  Map toMap() {
    return {
      'id': this.id,
      'stock': this.stock,
      'desc': this.desc,
      'filled': this.filled,
      'quantity': this.quantity,
      'price': this.price,
    };
  }
}

结果:

Product product = Product(...);
Map map = product.toMap();
String json = jsonEncode(map);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-28
    • 2013-09-06
    • 2020-06-13
    • 1970-01-01
    • 2014-05-31
    • 2012-11-14
    • 2023-03-10
    相关资源
    最近更新 更多