【问题标题】:Flutter: json_serializable ignore nullable fields instead of throwing an errorFlutter:json_serializable 忽略可空字段而不是抛出错误
【发布时间】:2021-05-23 10:02:30
【问题描述】:

假设有两个模型UserCity

@JsonSerializable()
class User {
    int id;
    String name;
    City? city;
    List<Map<String, City>>? listMapCity;

}

@JsonSerializable()
class City {
   int id;
   String name;
}

现在假设在 API 调用期间,我们有一个用户模型,但在城市对象模型中,我们只得到 id 而不是 name。像这样的

{
    "id": 5,
    "name": "Matthew",
    "city": {
        "id": 12
    }
}

但是由于 json_serializable 和 json_annotation 的默认性质。 此 JSON 未映射到 User 模型,在映射期间,它会引发异常。
type Null 不是 String 类型的子类型。 (因为这里 name 键在 city 对象中丢失)

但正如我们已经在 User 对象中声明 City 是可选的,我希望它应该解析带有 citylistMapCity 为 null 的 User JSON。

任何帮助或解决方案将不胜感激,谢谢

【问题讨论】:

  • 你使用的是什么 Dart 版本?如果您使用的是 Dart 2.12+,那么您应该将 City 对象中的 name 字段标记为可为空 - String? name
  • 我正在使用 Dart 2.13,但如果城市对象即将到来,我不希望名称是可选的,那么 id 和 name 都应该出现。
  • 目前在iOS中,我正在使用这个库github.com/JohnSundell/Unbox,这个工作就像我解释的那样。
  • 如果只有 id 并且 name 不存在,你想做什么?
  • 嗯,应该创建一个用户模型,城市为空。

标签: flutter dart dart-null-safety json-serializable


【解决方案1】:

您需要在 JsonSerializable User 类上有一个默认构造函数。然后,如果name 应该可以为空,则使用可以为空的String? name; 声明它

这是更新后的 User 类。

import 'package:json_annotation/json_annotation.dart';

part 'user.g.dart';

@JsonSerializable()
class User {
  int id;
  String name;
  City? city;
  List<Map<String, City>>? listMapCity;

  User({required this.id, required this.name, this.city, this.listMapCity});

  factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);

  Map<String, dynamic> toJson() => _$UserToJson(this);
}

@JsonSerializable()
class City {
  int id;
  String name;
  City({required this.id, required this.name});
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-27
    • 1970-01-01
    相关资源
    最近更新 更多