如何使用冻结忽略空值toJson?

Afd*_*dra 3 flutter flutter-dependencies json-serializable flutter-freezed

我尝试创建一个这样的轮廓模型;fromJson看起来不错,但我有一个问题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);
}
Run Code Online (Sandbox Code Playgroud)

我看到调试 toJson 将发送:

"attributes": {
   "_id": null,
   "uid": null,
   "username": null,
   "name": null,
   "phone": null,
   "email": "asdasda@gmasd.com",
   "address": null,
   "image": null
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我只想向后端发送电子邮件,例如:

"attributes": {
   "email": "asdasda@gmasd.com"
}
Run Code Online (Sandbox Code Playgroud)

如何忽略 中的空值toJson

mig*_*uno 8

在您希望在为 null 时不包含的每个字段上使用@JsonKey(includeIfNull: false)( docs ),或者如果您不想包含任何字段,则在类级别上使用@JsonSerializable(includeIfNull: false)( docs )

例子:

@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);
}
Run Code Online (Sandbox Code Playgroud)

生成这个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;
}
Run Code Online (Sandbox Code Playgroud)

注意这个函数的最后 4 行