如何使用 json_serializable 从 json 序列化中排除单个字段?

Sve*_*ven 0 dart flutter

我使用https://pub.dev/packages/json_serializable为我的类生成 Json 序列化。这工作正常。现在我想只为 json 生成忽略单个字段,但在读取 json 时不忽略,例如以下示例中的 dateOfBirth:

@JsonSerializable()
class Person {
  final String firstName;
  final String lastName;
  final DateTime dateOfBirth; //<-- ignore this field for json serialization but not for deserialization
  Person({this.firstName, this.lastName, this.dateOfBirth});
  factory Person.fromJson(Map<String, dynamic> json) => _$PersonFromJson(json);
  Map<String, dynamic> toJson() => _$PersonToJson(this);
}
Run Code Online (Sandbox Code Playgroud)

当我使用JsonKey.ignore该字段时,toJsonand 会被忽略fromJson。

是否有我缺少的这种情况的 JsonKey 注释?

小智 9

作为该包的最新版本,它应该是这样的:

@JsonKey(includeFromJson: false, includeToJson: false)
final String documentID; 
Run Code Online (Sandbox Code Playgroud)


Val*_*ova 7

使用空安全,它可以是:

@JsonKey(ignore: true)
final String documentID;
Run Code Online (Sandbox Code Playgroud)


Nol*_*nce 6

这是我一直在使用的一种解决方法,因此我最终不会在我的 FB 数据库中存储两次 documentID,同时仍然可以在对象上使用它们:

@JsonSerializable()
class Exercise {
  const Exercise({
    @required this.documentID,
    // ...
  })  : assert(documentID != null);

  @JsonKey(toJson: toNull, includeIfNull: false)
  final String documentID;

  //...

  factory Exercise.fromJson(Map<String, dynamic> json) =>
      _$ExerciseFromJson(json);
  Map<String, dynamic> toJson() => _$ExerciseToJson(this);
}

Run Code Online (Sandbox Code Playgroud)

哪里toNull只是

toNull(_) => null;
Run Code Online (Sandbox Code Playgroud)

toJson 会将值设为 null,然后 includeIfNull 不会序列化该值。