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

Flutter中jsonDecode无法将JSON键解析为整数类型的问题

解决JSON解析时将字符串键转为int键的问题

JSON规范里键只能是字符串类型,所以jsonDecode默认会把解析后的Map键设为String,直接强制转Map<int, String>就会报类型不匹配的错误:

_TypeError (type '_Map<String, dynamic>' is not a subtype of type 'Map<int, String>')

要得到键为int类型的Map,需要手动遍历解析后的原始Map,把每个键转成int,同时把值转为String:

基础实现方案

String json = "{ \"1\": \"test\", \"2\": \"test\" }";
// 先解析成默认的String键Map
Map<String, dynamic> rawMap = jsonDecode(json);
// 转换为int键的Map
Map<int, String> intKeyMap = {
  for (var entry in rawMap.entries)
    int.parse(entry.key): entry.value as String
};

容错处理方案(避免非法键/值报错)

如果JSON里可能存在非数字格式的键,或者值不是String类型,可以加判断跳过非法项:

String json = "{ \"1\": \"test\", \"2\": \"test\", \"abc\": 123 }";
Map<String, dynamic> rawMap = jsonDecode(json);
Map<int, String> intKeyMap = {};

for (var entry in rawMap.entries) {
  // 尝试把键转成int,失败则跳过
  final int? key = int.tryParse(entry.key);
  // 确保值是String类型
  if (key != null && entry.value is String) {
    intKeyMap[key] = entry.value;
  }
}

这样就能得到符合需求的Map<int, String>,即使JSON数据量很大,遍历转换的开销也在可接受范围内。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 18:15:12