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

Dio解析报错:_InternalLinkedHashMap无法转为String类型求助

Dart JSON解析错误:_InternalLinkedHashMap<String, dynamic> 不是 String 的子类型

问题概述

使用Dio发起API请求后,response.data 及 apiSTLData['store'] 的类型均为 _InternalLinkedHashMap<String, dynamic>,调用 StoreSTLModel.fromJson(apiSTLData['store']) 时触发错误:

Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'String'

核心原因

  1. Dio自动解析JSON:Dio默认会将API返回的JSON响应自动解析为Map<String, dynamic>(即_InternalLinkedHashMap),无需手动调用json.decode。
  2. 方法参数类型不匹配:StoreSTLModel.fromJson 方法定义的参数是String类型的JSON字符串,但你传入的apiSTLData['store']是已经解析完成的Map对象,类型完全不匹配,因此报错。

解决方案

方案一:直接调用fromMap方法(推荐)

既然apiSTLData['store']已经是Map类型,直接使用fromMap方法完成解析:
修改请求代码中的返回语句:

return StoreSTLModel.fromMap(apiSTLData['store'] as Map<String, dynamic>);

方案二:兼容fromJson方法的参数类型

如果希望保留fromJson的调用方式,可以修改该方法,使其同时支持String和Map类型的输入:

factory StoreSTLModel.fromJson(dynamic source) {
  if (source is String) {
    return StoreSTLModel.fromMap(json.decode(source) as Map<String, dynamic>);
  } else if (source is Map<String, dynamic>) {
    return StoreSTLModel.fromMap(source);
  }
  throw ArgumentError('fromJson仅支持String或Map<String, dynamic>类型');
}

修改后原调用语句StoreSTLModel.fromJson(apiSTLData['store'])即可正常执行。

额外说明

  • 若需要获取API返回的原始JSON字符串,可使用response.toString(),或配置Dio禁用自动解析:
    Dio dio = Dio(BaseOptions(responseType: ResponseType.plain));
    
  • 你的StoreSTLModel仅使用了store对象中的部分字段,JSON解析时会自动忽略未定义的字段,无需额外处理。

内容的提问来源于stack exchange,提问作者Lady Geraldine Villamil Guerre

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 06:45:34