flutterflutter-dependenciesflutter-freezedjson-serializable

How to ignore null value toJson using freezed?


I've tried to create a profile model like this; fromJson looks good, but I have a problem with toJson:

@Freezed(
  fromJson: true,
  toJson: true,
  map: FreezedMapOptions.none,
  when: FreezedWhenOptions.none,
)
class ProfileAttribute with _$ProfileAttribute {
  const factory ProfileAttribute({
    @JsonKey(name: '_id', includeIfNull: false) final String? id,
    final String? uid,
    final String? username,
    final String? name,
    final String? phone,
    final String? email,
    final String? address,
    final String? image,
  }) = _ProfileAttribute;

  factory ProfileAttribute.fromJson(Map<String, dynamic> json) =>
      _$ProfileAttributeFromJson(json);
}

I see on debug toJson will send:

"attributes": {
   "_id": null,
   "uid": null,
   "username": null,
   "name": null,
   "phone": null,
   "email": "asdasda@gmasd.com",
   "address": null,
   "image": null
}

In this case, I just want to send email to backend like:

"attributes": {
   "email": "asdasda@gmasd.com"
}

How to ignore null value in toJson?


Solution

  • Use @JsonKey(includeIfNull: false) (docs) on every field you want not included when null, or @JsonSerializable(includeIfNull: false) (docs) on a class level if you don't want to include any

    Example:

    @freezed
    class Person with _$Person {
    
      @JsonSerializable(includeIfNull: false)
      const factory Person({
        String? firstName,
        String? lastName,
        int? age,
      }) = _Person;
    
      factory Person.fromJson(Map<String, Object?> json) => _$PersonFromJson(json);
    }
    

    generates this toJson:

    Map<String, dynamic> _$$_PersonToJson(_$_Person instance) {
      final val = <String, dynamic>{};
    
      void writeNotNull(String key, dynamic value) {
        if (value != null) {
          val[key] = value;
        }
      }
    
      writeNotNull('firstName', instance.firstName);
      writeNotNull('lastName', instance.lastName);
      writeNotNull('age', instance.age);
      return val;
    }
    

    notice the last 4 lines of this function