【问题标题】:Dart json.decode can't decode to Map<String, String>Dart json.decode 无法解码为 Map<String, String>
【发布时间】:2019-07-06 18:35:08
【问题描述】:

我的代码:

import 'dart:convert';

String jsonString = '''{
"a": "g",
"b": "h",
"c": "j",
"d": "k"
}''';

Map<String, String> map = json.decode(jsonString);

得到错误:

Unhandled exception:
type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Map<String, String>'
#0      main (file:///...)
#1      _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:298:32)
#2      _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:171:12)

Map&lt;String, dynamic&gt; map ...Map&lt;String, Object&gt; map ... 正在工作。

我最终尝试为不同的 JSON 反序列化 Map&lt;String, Map&gt;,它给了我同样的错误,所以我决定首先使用基本的 Map&lt;String, String&gt;,以更好地了解我做错了什么

【问题讨论】:

  • 试试Map&lt;String, String&gt; data = Map.castFrom(json.decode(jsonString))。如果这仍然失败,请检查您的 JSON 数据中的所有值是否都是字符串类型
  • 这是有效的,你能把这个作为答案发布吗?

标签: json dart


【解决方案1】:

要确保将 JSON 转换为指定值,请使用 Map.castFrom 方法。

所以你的代码变成了

import 'dart:convert';

void main () {
  String jsonString = '''
{
  "a": "g",
  "b": "h",
  "c": "j",
  "d": "k"
}''';

  Map<String, String> map = Map.castFrom(json.decode(jsonString));
  print(map);
}

请注意,如果类型不兼容,它将抛出。您应该始终考虑处理它。

【讨论】:

    【解决方案2】:

    当我使用 firebase 消息传递时。我强制这样做接收通知的正文。我不知道原因,但我是这样解决的:

    Map<String, String> valueMap = Map.castFrom(json.decode(json.decode(payload!)));
    

    【讨论】:

      猜你喜欢
      • 2023-03-27
      • 1970-01-01
      • 2020-12-18
      • 2021-03-25
      • 2019-03-15
      • 2020-01-10
      • 1970-01-01
      • 2019-03-04
      • 1970-01-01
      相关资源
      最近更新 更多