忽略属性build_runner的序列化标记

29

有没有办法在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 */};
4个回答

65

2
当您使用继承时,似乎这并不起作用... - Joaquin Iurchuk
5
如何使其仅忽略 toJson 方法? - buncis
2
之前用词不当,我的使用情况是:有一个“属性”,我想把它从JSON转换到我的模型中,但我希望在从模型创建JSON时忽略它。希望这个回复能够澄清。 - buncis
1
@buncis 我想我明白了,但我还没有解决方案。 - Günter Zöchbauer
1
@buncis 有同样的需求,我找到了解决方案。只需添加此键 @JsonKey(toJson: null, includeIfNull: false) - 此字段将从 toJson 指令中删除。 - awaik
显示剩余4条评论

13

折旧警告

@Deprecated(
      'Use `includeFromJson` and `includeToJson` with a value of `false` '
      'instead.',
    )
this.ignore,

正如 @Peking 提到的那样, 新方法是在fromJson和toJson函数中指定添加或删除。

@JsonKey(includeFromJson: true, includeToJson: false)

NEW:

@Günter Zöchbauer提到过,旧的方式是通过将ignore: true传递给JsonKey来实现。

@JsonKey(ignore: true)
String value;

6
一种解决方法是将属性设置为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;
}

我已经检查了这种方法,但它并不起作用。收到User的someReadOnlyProperty参数是非空的,但既不是必需的也没有标记为@Default @Andrey Gordeev - genericUser
如果有人知道与“Freeze”相关的有效解决方案,请回答这个问题:https://dev59.com/RMn6oIgBc1ULPQZFevYK - genericUser
@genericUser 你是不是忘记加上 @Default 了? - Andrey Gordeev
是的!感谢 @Andrey Gordeev - genericUser

0

@JsonKey(includeFromJson: false, includeToJson: false)

@JsonKey(includeFromJson:false,includeToJson:false)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接