Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to ignore null value toJson using freezed?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

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

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

so, how to ignore null value 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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading