标记忽略 属性 build_runner 的序列化

Flag to ignore serialization of property build_runner

有没有办法在 JsonSerializable class 中忽略 属性 的序列化?

我正在使用 build_runner 生成映射代码。

实现此目的的一种方法是在 .g.dart 文件中注释特定 属性 的映射,但如果可以在 [=28] 上添加忽略属性会更好=].

import 'package:json_annotation/json_annotation.dart';

part 'example.g.dart';

@JsonSerializable()
class Example {
  Example({this.a, this.b, this.c,});

  int a;
  int b;

  /// Ignore this property
  int c;

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

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

结果是

Example _$ExampleFromJson(Map<String, dynamic> json) {
  return Example(a: json['a'] as int, b: json['b'] as int, c: json['c'] as int);
}

Map<String, dynamic> _$ExampleToJson(Example instance) =>
    <String, dynamic>{'a': instance.a, 'b': instance.b, 'c': instance.c};

我通过注释 c 的映射来实现这一点。

Example _$ExampleFromJson(Map<String, dynamic> json) {
  return Example(a: json['a'] as int, b: json['b'] as int, c: json['c'] as int);
}

Map<String, dynamic> _$ExampleToJson(Example instance) =>
    <String, dynamic>{'a': instance.a, 'b': instance.b, /* 'c': instance.c */};

在您不想包含的字段前添加 @JsonKey(ignore: true)

 @JsonKey(ignore: true)
 int c;

另见 https://github.com/dart-lang/json_serializable/blob/06718b94d8e213e7b057326e3d3c555c940c1362/json_annotation/lib/src/json_key.dart#L45-L49

解决方法是将 属性 设置为 null 并将 includeIfNull 标志设置为 false:

toNull(_) => null;

@freezed
class User with _$User {
  const factory User({
    ...

    @Default(false)
    @JsonKey(toJson: toNull, includeIfNull: false)
        bool someReadOnlyProperty,
  }) = _User;

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

生成的代码是:

/// user.g.dart

Map<String, dynamic> _$$_UserToJson(_$_User instance) {
  final val = <String, dynamic>{
    ...
  };

  void writeNotNull(String key, dynamic value) {
    if (value != null) {
      val[key] = value;
    }
  }

  writeNotNull('someReadOnlyProperty', toNull(instance.someReadOnlyProperty));
  return val;
}