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

Flutter如何从模型生成仅包含非空值的JSON对象

解决Flutter生成JSON时移除空/Null字段的问题

这里给你几种实用的修改方案,按需选择:

方案1:手动构建Map(适合简单场景)

先创建空Map,只添加非Null的字段,避免无效键值对:

var json = {};
if (bloodTest != null) json["bloodTest"] = bloodTest;
if (info.weight != null) json["weight"] = info.weight;
if (info.height != null) json["height"] = info.height;
if (info.profile?.id != null) json["profile"] = info.profile.id;

如果需要处理空列表(比如bloodTest是空数组时也要移除),可以把判断条件改成bloodTest != null && bloodTest.isNotEmpty。

方案2:过滤已有Map的Null值

先保留你原来的写法,再统一过滤掉值为Null的键:

var json = {
  "bloodTest": bloodTest,
  "weight": info.weight,
  "height": info.height,
  "profile": info.profile?.id,
}..removeWhere((key, value) => value == null);

这个方法更简洁,适合字段较多的场景。注意用空安全操作符?.处理info.profile.id,避免因info.profile为Null引发报错。

方案3:用json_serializable库(适合复杂模型场景)

如果你的项目使用json_serializable生成JSON序列化代码,可以给模型字段添加@JsonKey(includeIfNull: false)注解,自动忽略Null字段:

import 'package:json_annotation/json_annotation.dart';

part 'info_model.g.dart';

@JsonSerializable()
class Info {
  final List<String>? bloodTest;
  
  @JsonKey(includeIfNull: false)
  final int? weight;
  
  @JsonKey(includeIfNull: false)
  final int? height;
  
  final Profile? profile;

  Info({this.bloodTest, this.weight, this.height, this.profile});

  factory Info.fromJson(Map<String, dynamic> json) => _$InfoFromJson(json);
  Map<String, dynamic> toJson() => _$InfoToJson(this);
}

@JsonSerializable()
class Profile {
  final String id;

  Profile({required this.id});

  factory Profile.fromJson(Map<String, dynamic> json) => _$ProfileFromJson(json);
  Map<String, dynamic> toJson() => _$ProfileToJson(this);
}

生成代码后,调用info.toJson()就会自动移除Null字段。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 19:22:08