How to ignore null value toJson using freezed?
Asked Answered
T

1

5

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": "[email protected]",
   "address": null,
   "image": null
}

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

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

How to ignore null value in toJson?

Thurmond answered 12/11, 2022 at 14:15 Comment(0)
L
11

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

Ligroin answered 12/11, 2022 at 14:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.