【问题标题】:How to convert a Set in Map to json in flutter with dart如何使用飞镖将地图中的集合转换为 json
【发布时间】:2021-10-28 21:13:35
【问题描述】:

我是 Flutter 的新手,遇到以下类的 json 序列化问题:

class Profile {
  DatabaseReference _id;
  String userId;  // related to Google UserId
  Map<String,Set> attrs;  // String is the key and the Set includes all possible value
}

Profile 类中的 Map 有一个 String 作为 key,一个 Set 作为它的 value,它会像:

attrs = [{"food":["beef","fish","pork"]},{"work_experience":["company1","company2"],...}]

有没有好的解决方案来序列化/反序列化类 toJson/fromJson?

【问题讨论】:

    标签: json flutter serialization deserialization


    【解决方案1】:

    只需破坏您的 json 文件,它将提供序列化模型

    https://javiercbk.github.io/json_to_dart/

    【讨论】:

      【解决方案2】:

      你可以这样使用。

      class Profile {
        var _id;
        String? userId; // related to Google UserId
        late Map<String, Set>
            attrs; // String is the key and the Set includes all possible value
      
        Profile.fromJson(Map<String, dynamic> json) {
          attrs = Map();
          var attrsVal = json["attrs"];
          attrsVal.forEach((e) {
            MapEntry entry = e.entries.first;
            attrs.putIfAbsent(entry.key, () => entry.value.toSet());
          });
        }
      
        toJson() {
          return Map<String, dynamic>()
            ..putIfAbsent("id", () => _id)
            ..putIfAbsent("userId", () => userId)
            ..putIfAbsent(
                "attrs", () => [attrs.map((k, v) => MapEntry(k, v.toList()))]);
        }
      
      }
      

      【讨论】:

        猜你喜欢
        • 2020-05-10
        • 2021-04-12
        • 1970-01-01
        • 1970-01-01
        • 2021-06-21
        • 1970-01-01
        • 1970-01-01
        • 2021-10-07
        • 1970-01-01
        相关资源
        最近更新 更多