Flutter:json_serialized 忽略可为 null 的字段而不是抛出错误

Him*_*ora 11 dart flutter json-serializable dart-null-safety

假设有两个模型UserCity

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

}

@JsonSerializable()
class City {
   int id;
   String name;
}
Run Code Online (Sandbox Code Playgroud)

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

{
    "id": 5,
    "name": "Matthew",
    "city": {
        "id": 12
    }
}
Run Code Online (Sandbox Code Playgroud)

但由于 json_serialized 和 json_annotation 的默认性质。该 JSON 未映射到 User 模型,在映射期间,它会抛出异常。
Null 类型不是 String 类型的子类型。(因为这里城市对象中缺少名称键)

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

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

swe*_*tfa 15

您需要将 includeIfNull 标志设置为 false 才能让自动生成的代码正确处理空值。

@JsonSerializable(includeIfNull: false)
Run Code Online (Sandbox Code Playgroud)

该财产应该用 ? 来声明。按照你的例子。


Oma*_*att 2

您的 JsonSerialized 类需要有一个默认构造函数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});
}
Run Code Online (Sandbox Code Playgroud)