Dart json.decode无法解码为Map< String,String> [英] Dart json.decode can't decode to Map<String, String>

查看:839
本文介绍了Dart json.decode无法解码为Map< String,String>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码:

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<String, dynamic> map ...Map<String, Object> map ... 在工作.

我试图在结尾Map<String, Map>中针对不同的JSON进行反序列化,它给了我相同的错误,因此我决定首先使用Map<String, String>的基础知识来更好地理解我在做什么错

I am trying to de serialize in the end Map<String, Map> for different JSON and it gave me the same error so I have decided to first work with the basic which is the Map<String, String> to better understand what am I doing wrong

推荐答案

要确保将JSON强制转换为指定值,请使用

To make sure the JSON is cast to the specified value use the Map.castFrom method.

因此您的代码变为

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);
}

请注意,如果类型不兼容,则会抛出该错误.您应该始终考虑处理该问题.

Note that if the types are incompatible it will throw. You should always consider handling that.

这篇关于Dart json.decode无法解码为Map&lt; String,String&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆