Ale*_*lex 14 dart flutter json-serialization
有没有办法忽略 JsonSerializable 类中属性的序列化?
我正在使用 build_runner 生成映射代码。
实现此目的的一种方法是在 .g.dart 文件中注释该特定属性的映射,尽管如果可以在属性上添加 ignore 属性会很棒。
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);
}
Run Code Online (Sandbox Code Playgroud)
这导致
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};
Run Code Online (Sandbox Code Playgroud)
我所做的就是通过注释 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 */};
Run Code Online (Sandbox Code Playgroud)
Gün*_*uer 33
@JsonKey(ignore: true)在不想包含的字段前添加
@JsonKey(ignore: true)
int c;
Run Code Online (Sandbox Code Playgroud)
小智 13
@Deprecated(\n \'Use `includeFromJson` and `includeToJson` with a value of `false` \'\n \'instead.\',\n )\nthis.ignore,\nRun Code Online (Sandbox Code Playgroud)\n正如@Peking提到的\n新方法是指定是否在 fromJson 和 toJson 函数中添加或删除
\n@JsonKey(includeFromJson: true, includeToJson: false)\nRun Code Online (Sandbox Code Playgroud)\n正如 @G\xc3\xbcnter Z\xc3\xb6chbauer 提到的\n旧方法是传递ignore: true给JsonKey
@JsonKey(ignore: true)\nString value;\nRun Code Online (Sandbox Code Playgroud)\n
解决方法是将属性设置为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);
}
Run Code Online (Sandbox Code Playgroud)
生成的代码是:
/// 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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4559 次 |
| 最近记录: |