Is there a way to ignore the serialization of a property within a JsonSerializable class?
I'm using build_runner to generate the mapping code.
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.
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.
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 */};
Depreciation warning
@Deprecated(
'Use `includeFromJson` and `includeToJson` with a value of `false` '
'instead.',
)
this.ignore,
NEW
As @Peking mentioned The new way is to specify whether to add or remove in fromJson and toJson functions
@JsonKey(includeFromJson: true, includeToJson: false)
OLD:
As @Günter Zöchbauer mentioned
The old way is by passing ignore: true
to the JsonKey
@JsonKey(ignore: true)
String value;