簡體   English   中英

標志忽略屬性 build_runner 的序列化

[英]Flag to ignore serialization of property build_runner

有沒有辦法忽略 JsonSerializable 類中屬性的序列化?

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

實現此目的的一種方法是在 .g.dart 文件中注釋該特定屬性的映射,盡管如果可以在屬性上添加忽略屬性會很棒。

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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM