Sven
Sven

Reputation: 1887

How to exclude a single field from json serialization with json_serializable?

I use https://pub.dev/packages/json_serializable to generate Json serialization for my classes. This works fine. Now I would like to ignore a single field only for the json generation but not when reading a json e.g. the dateOfBirth in following example:

@JsonSerializable()
class Person {
  final String firstName;
  final String lastName;
  final DateTime dateOfBirth; //<-- ignore this field for json serialization but not for deserialization
  Person({this.firstName, this.lastName, this.dateOfBirth});
  factory Person.fromJson(Map<String, dynamic> json) => _$PersonFromJson(json);
  Map<String, dynamic> toJson() => _$PersonToJson(this);
}

When I use JsonKey.ignore the field is ignored for toJson and fromJson.

Is there a JsonKey Annotation for this case that I am missing?

Upvotes: 13

Views: 11179

Answers (3)

ABDO-AR
ABDO-AR

Reputation: 344

As the latest version of the package it should be like that:

@JsonKey(includeFromJson: false, includeToJson: false)
final String documentID; 

Upvotes: 12

Nolence
Nolence

Reputation: 2274

Here's a workaround I've been using so I don't end up storing documentID's twice in my FB database while still having them available on the objects:

@JsonSerializable()
class Exercise {
  const Exercise({
    @required this.documentID,
    // ...
  })  : assert(documentID != null);

  static toNull(_) => null; 
  @JsonKey(toJson: toNull, includeIfNull: false)
  final String documentID;

  //...

  factory Exercise.fromJson(Map<String, dynamic> json) =>
      _$ExerciseFromJson(json);
  Map<String, dynamic> toJson() => _$ExerciseToJson(this);
}

where toNull is just

toNull(_) => null;

The toJson will null the value and then the includeIfNull won't serialize the value.

Upvotes: 20

Valentina Konyukhova
Valentina Konyukhova

Reputation: 5334

With null safety it can be:

@JsonKey(ignore: true)
final String documentID;

Upvotes: 24

Related Questions