【问题标题】:Is it possible to parse json in Flutter/Dart with missing attributes?是否可以在 Flutter/Dart 中解析缺少属性的 json?
【发布时间】:2022-01-12 19:25:24
【问题描述】:

我有来自 API 的 json 形式的对象列表。这些对象有一些属性,问题是一些对象缺少属性。那么如何正确解析其他属性的数据呢?

例如我有这个缺少paymentType的属性

"user":{
"id": 6,
"name": "User",
"email": "",
"phone": "123",
"credit": null,
"fireBaseId": null,
"created_at": "2021-10-28T10:28:34.000000Z",
"updated_at": "2021-10-29T22:10:09.000000Z"
},
"paymentType": null,
"booking_type":{
"id": 1,
"name": "Mobile",
"price": 0,
"created_at": null,
"updated_at": null
}

但这所有属性都存在:

"user":{
"id": 6,
"name": "User",
"email": "",
"phone": "",
"credit": null,
"fireBaseId": null,
"created_at": "2021-10-28T10:28:34.000000Z",
"updated_at": "2021-10-29T22:10:09.000000Z"
},
"paymentType":{
"id": 1,
"name": "Cash",
"active": 1,
"created_at": "2021-10-29T00:36:06.000000Z",
"updated_at": "2021-10-29T17:24:42.000000Z"
},
"booking_type":{
"id": 2,
"name": "Parking",
"price": 10,
"created_at": null,
"updated_at": null
}

【问题讨论】:

    标签: json flutter dart


    【解决方案1】:

    如果您觉得某些属性可能为空,请为其添加空安全,然后使用 if() 条件将映射中的值解析为对象的属性。

    这是一种可能的方式。它可能不是理想的,但效果很好!

    class User {
      int? id;
      String? user;
      String? email;
      String? phone;
      String? credit;
    
      User.fromMap(Map<String, dynamic> map) {
        if (map.containsKey('id')) {
          this.id = int.parse(map['id']);
        }
        if (map.containsKey('user')) {
          this.user = "${map['user']}";
        }
        if (map.containsKey('email')) {
          this.email = "${map['email']}";
        }
        if (map.containsKey('phone')) {
          this.phone = "${map['phone']}";
        }
        if (map.containsKey('credit')) {
          this.credit = "${map['credit']}";
        }
      }
    }
    

    【讨论】:

      【解决方案2】:

      您可以为 paymentType 创建特殊的对象类。试试看吧。

      创建 payment.dart

      class PaymentType {
        int id;
        String name;      
        int active;
        DateTime createdAt;
        DateTime updatedAt;
      
        PaymentType({
          this.id,
          this.name,
          this.active,
          this.createdAt,
          this.updatedAt,
        }) ;
      
        factory PaymentType.fromJson(Map<String, dynamic> json) =>PaymentType(
              id: json["id"],
              name: json["name"],
              active: json["active"],
              createdAt: DateTime.parse(json["created_at"]),
              updatedAt: DateTime.parse(json["updated_at"]),
            );
      }
      

      并在解析时这样使用它:

      ......
      "paymentType" : json["payment_type"] != null ? PaymentType.fromJson(json["payment_type"]) : null;
      ......
      

      如果您有任何疑问,请随意:)

      【讨论】:

      • 不适合我,无论如何谢谢
      猜你喜欢
      • 2021-08-13
      • 2020-11-25
      • 1970-01-01
      • 2021-02-09
      • 1970-01-01
      • 2021-07-10
      • 2022-01-09
      • 2013-12-12
      • 2016-01-30
      相关资源
      最近更新 更多