You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Freezed在toJson序列化时忽略Null值?

解决Freezed模型toJson时忽略Null值字段的问题

你可以通过两种方式实现只保留非Null字段的toJson输出:

方法一:全局配置(推荐)

在@Freezed注解中添加jsonKey参数,全局设置所有可选字段在值为Null时不参与序列化:

@Freezed(
  fromJson: true,
  toJson: true,
  map: FreezedMapOptions.none,
  when: FreezedWhenOptions.none,
  jsonKey: const JsonKey(includeIfNull: false), // 全局生效的Null忽略规则
)
class ProfileAttribute with _$ProfileAttribute {
  const factory ProfileAttribute({
    @JsonKey(name: '_id') final String? id, // 仅保留name映射,includeIfNull继承全局配置
    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);
}

方法二:单独配置每个字段

如果需要针对特定字段设置规则,可以给每个nullable字段添加@JsonKey(includeIfNull: false)注解:

@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,
    @JsonKey(includeIfNull: false) final String? uid,
    @JsonKey(includeIfNull: false) final String? username,
    @JsonKey(includeIfNull: false) final String? name,
    @JsonKey(includeIfNull: false) final String? phone,
    @JsonKey(includeIfNull: false) final String? email,
    @JsonKey(includeIfNull: false) final String? address,
    @JsonKey(includeIfNull: false) final String? image,
  }) = _ProfileAttribute;

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

注意事项

修改注解后必须重新运行代码生成命令,让Freezed更新序列化逻辑:

flutter pub run build_runner build
# 或者纯Dart项目用
dart run build_runner build

这样处理后,你的toJson输出就只会包含有实际值的字段,符合预期的格式。

内容的提问来源于stack exchange,提问作者Afdal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 11:15:36