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

Dart中Set<Map>转JSON报错及JSON转Set<Map>方法咨询

问题解决:Set<Map<String, dynamic>>与JSON的相互转换

一、解决Set转JSON字符串的错误

触发NoSuchMethodError的原因是Dart的jsonEncode默认不支持直接序列化Set类型——JSON规范里没有对应Set的结构,标准JSON数组对应Dart的List。

修改代码只需将Set转换为List后再序列化:

final intSets = Set<Map<String, dynamic>>.from(
  ids.map((x) => (x as IdModel).toMap()),
);

// 修正:将Set转为List后再编码
final intSetString = jsonEncode(intSets.toList());

二、将JSON字符串转回Set<Map<String, dynamic>>

可以通过先解码得到List,再将List转换为Set的方式实现:

// 解码JSON字符串得到List
final decodedList = jsonDecode(intSetString) as List<dynamic>;
// 将List转换为Set<Map<String, dynamic>>
final intSetsFromJson = decodedList.cast<Map<String, dynamic>>().toSet();

补充说明:

  • jsonDecode会把JSON数组解析为Dart的List<dynamic>
  • cast<Map<String, dynamic>>()用于将列表元素统一转换为目标Map类型
  • 最后调用toSet()完成List到Set的转换

内容的提问来源于stack exchange,提问作者Daniel Roldán

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 15:38:12