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

Flutter中如何将动态结构JSON正确转换为对应数据模型

Flutter动态键名嵌套JSON的模型转换方法

在Flutter开发中,固定结构的常规JSON转数据模型流程非常简单。
首先参考基础的固定结构JSON示例:

jsonData = {'id':'1','name':'modelItem'} 

针对这类键名固定的结构,只需要定义对应字段的模型类即可完成转换:

class Model{
  final String? id;
  final String? name;

  Model({this.id,this.name});
}

遇到键名动态的嵌套JSON时,固定字段的模型写法就不再适用,常见的动态结构有两类:

  • 外层键动态,内层结构固定:
jsonData= {'NYC':{'city code':'NYC','country code':'US'}}
  • 多层键均为动态:
jsondata= {'NYC': {'NYC':'NEW YORK'}}

核心处理思路

不要把无法预知的动态键硬编码为模型字段,用Map类型承接动态键层,仅对内层结构固定的部分单独定义模型即可。
具体实现逻辑:

  • 拆分JSON结构,明确哪些层的键是动态变化的,哪些层的字段结构是固定的
  • 动态键层直接用Map<String, 对应值类型>作为字段类型,遍历JSON的键值对完成转换
  • 内层结构固定的部分,按照常规方式写序列化逻辑即可

对应场景的代码实现

场景1:外层动态键+内层固定结构

针对第一个动态JSON示例,先定义内层固定的城市信息模型,外层用Map承接动态键:

// 内层固定结构:城市基础信息
class CityInfo {
  final String? cityCode;
  final String? countryCode;

  CityInfo({this.cityCode, this.countryCode});

  factory CityInfo.fromJson(Map<String, dynamic> json) {
    return CityInfo(
      cityCode: json['city code'] as String?,
      countryCode: json['country code'] as String?,
    );
  }
}

// 外层承接动态城市键
class DynamicCityModel {
  // key为动态的城市编码,value为对应城市的固定信息
  final Map<String, CityInfo> cityMap;

  DynamicCityModel({required this.cityMap});

  factory DynamicCityModel.fromJson(Map<String, dynamic> json) {
    final Map<String, CityInfo> tempMap = {};
    // 遍历所有动态键,逐个解析内层固定结构
    json.forEach((cityKey, cityValue) {
      tempMap[cityKey] = CityInfo.fromJson(cityValue as Map<String, dynamic>);
    });
    return DynamicCityModel(cityMap: tempMap);
  }
}

使用时直接调用DynamicCityModel.fromJson(jsonData)即可完成转换,取数时通过cityMap['NYC']?.countryCode就能拿到纽约对应的国家码,无论外层有多少个动态新增的城市键都可以正常适配。

场景2:多层键均为动态

针对第二个两层键都动态的示例,不需要额外定义内层模型,直接嵌套Map承接即可:

class DynamicCityAliasModel {
  // 外层key为城市编码,内层key为动态简称,value为对应全称
  final Map<String, Map<String, String>> cityAliasMap;

  DynamicCityAliasModel({required this.cityAliasMap});

  factory DynamicCityAliasModel.fromJson(Map<String, dynamic> json) {
    final Map<String, Map<String, String>> tempMap = {};
    json.forEach((outerKey, outerValue) {
      tempMap[outerKey] = Map<String, String>.from(outerValue as Map);
    });
    return DynamicCityAliasModel(cityAliasMap: tempMap);
  }
}

补充说明:如果项目中使用json_serializable、freezed等自动序列化库,处理这类动态结构不需要额外配置,只要将动态键对应的字段声明为Map<String, 值类型>,生成的代码会自动完成遍历转换逻辑。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 01:57:24