【问题标题】:Flutter: How to optionally serialize many list of data or object of data?Flutter:如何有选择地序列化许多数据列表或数据对象?
【发布时间】:2022-11-19 22:05:15
【问题描述】:

我想将来自 API 的可选 JSON 数据序列化为列表或对象。在这里,我有点重现 DjangoRestFramework 序列化程序在 Flutter 中的工作方式。您可以选择传递参数 many=Truemany=False 以指示将有大量数据(如列表)或只有一个数据(如对象)。这是它在 Django 中的样子

serializer = BookSerializer(queryset, many=True)

我在flutter中的序列化器目前只能序列化JSON数据列表,但没有序列化JSON数据对象的能力可选地.数据示例将是:

// Data as a list
{
    "message": "Berhasil mengambil profile User",
    "statusCode": 200,
    "data": [
        {
            "id": 1,
            "avatar": "32412"
        }
        .
        .
        .
        .
        {
            "id": 1,
            "avatar": "32412"
        }
    ]
}

// Data as an object
{
    "message": "Berhasil mengambil profile User",
    "statusCode": 200,
    "data": {
        "id": 1,
        "avatar": "32412"
    }
}

这是我当前的代码:

class UserProfileSeralizer {
  final String? message;
  final int? statusCode;
  final dynamic data;
  bool many = true;

  UserProfileSeralizer(this.many, {this.message, this.statusCode, this.data});

  factory UserProfileSeralizer.fromJson(Map<String, dynamic> json) {
    final message = json['message'];
    final statusCode = json['statusCode'];

    final tempDataJson = json['data'];
    // Assign data as List or as Data based on many's value
    if (many) {
      final List data = List.from(tempDataJson);
    } else {
      final Data data = Data.fromJson(tempDataJson);
    }

    return UserProfileSeralizer(
      message: message,
      statusCode: statusCode,
      data: data,
    );
  }
}

我以为我可以在工厂访问变量many并根据many的值分配data变量。所以我有点迷路了,需要帮助。

此致。

【问题讨论】:

    标签: json flutter serialization deserialization


    【解决方案1】:

    尝试这个:

    factory UserProfileSeralizer.fromJson(Map<String, dynamic> json) {
      return UserProfileSeralizer(json['data'] is List,
              message: json['message'],
              statusCode: json['statusCode'],
              data: json['data']);
    }
    

    【讨论】:

    • 抱歉,你能不能把代码扩展到类本身,我迷路了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-30
    • 2013-12-26
    • 1970-01-01
    • 2015-02-03
    • 1970-01-01
    • 1970-01-01
    • 2011-02-01
    相关资源
    最近更新 更多