Home > Net >  How to ignore null value toJson using freezed?
How to ignore null value toJson using freezed?

Time:11-13

i've try create profile model like this

fromJson look good, but i've 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": "[email protected]",
   "address": null,
   "image": null
}

on this case, i just wan't send email to Back End like:

"attributes": {
   "email": "[email protected]"
}

so, how to ignore null value toJson?

CodePudding user response:

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

  • Related