[英]Flag to ignore serialization of property build_runner
Is there a way to ignore the serialization of a property within a JsonSerializable class?有没有办法忽略 JsonSerializable 类中属性的序列化?
I'm using build_runner to generate the mapping code.我正在使用 build_runner 生成映射代码。
One way to achieve this is by commenting the mapping for that specific property within the .g.dart-file though it would be great if an ignore attribute could be added on the property.实现此目的的一种方法是在 .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);
}
Which results in这导致
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};
What I do to achieve this is by commenting the mapping of 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 */};
Add @JsonKey(ignore: true)
before the field that you don't want to include在不想包含的字段前添加
@JsonKey(ignore: true)
@JsonKey(ignore: true)
int c;
See also https://github.com/dart-lang/json_serializable/blob/06718b94d8e213e7b057326e3d3c555c940c1362/json_annotation/lib/src/json_key.dart#L45-L49另见https://github.com/dart-lang/json_serializable/blob/06718b94d8e213e7b057326e3d3c555c940c1362/json_annotation/lib/src/json_key.dart#L45-L49
A workaround is to set the property to null
and set includeIfNull
flag to false:解决方法是将属性设置为
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);
}
And the generated code is:生成的代码是:
/// 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.