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

如何处理JSON payload中的空嵌套Map?Flutter序列化问题

问题解决方法

首先看报错本质:你在PropertyInformation类里定义的features字段类型是Features?,但你却用处理Map集合的代码(和taxAssessment一样的逻辑)去解析,导致类型不匹配。结合你的JSON数据,features是一个单独的Map(哪怕是空的),对应单个Features对象,不是Map集合,所以解析逻辑要和owner字段一致,而非taxAssessment。

步骤1:修复Features类的构造函数

你的Features构造函数用了required修饰所有参数,但空Map解析时所有属性都是null,会触发错误。把构造函数改成可选命名参数,去掉required:

class Features {
  String? architectureType;
  bool? cooling;
  String? coolingType;
  String? exteriorType;
  int? floorCount;
  String? foundationType;
  bool? garage;
  String? garageType;
  bool? heating;
  String? heatingType;
  bool? pool;
  String? roofType;
  int? roomCount;
  int? unitCount;

  // 去掉所有required,改成可选参数
  Features({
    this.architectureType,
    this.cooling,
    this.coolingType,
    this.exteriorType,
    this.floorCount,
    this.foundationType,
    this.garage,
    this.garageType,
    this.heating,
    this.heatingType,
    this.pool,
    this.roofType,
    this.roomCount,
    this.unitCount,
  });

  // 其他代码保持不变...
}

步骤2:修正PropertyInformation里的features解析逻辑

把原来的Map处理逻辑删掉,换成单个对象的解析方式,同时适配空Map的情况:

factory PropertyInformation.fromJson(Map<String?, dynamic> json) {
  return PropertyInformation(
    // 其他字段保持不变...
    // 直接解析单个Features对象,空Map会生成所有属性为null的Features实例
    features: Features.fromJson(json['features'] as Map<String?, dynamic>),
    // taxAssessment等Map集合的解析逻辑不变...
  );
}

如果API返回的features可能为null(而非空Map),可以加空判断增强鲁棒性:

features: json['features'] != null 
    ? Features.fromJson(json['features'] as Map<String?, dynamic>)
    : null,

为什么之前的逻辑不对?

taxAssessment字段在API返回里是Map集合(比如{"2023": {...}, "2022": {...}}),所以需要用map方法把每个子Map转成TaxAssessment对象,最终得到Map<String?, TaxAssessment>类型。而features是单个Map,对应单个Features对象,所以直接调用fromJson即可,不需要转成Map集合。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 09:34:56