json解码后无法为我的Map <string,string =“”>变量赋值

时间:2019-01-14 22:00:47

标签: json dart flutter

在对json编码然后对其进行json解码之后,我尝试为Map<String, String>变量赋值。下面的代码示例是一个简化的复制;

import 'dart:convert';

String toJson(dynamic object) {
  var encoder = new JsonEncoder.withIndent("     ");
  return encoder.convert(object);
}

dynamic fromJson(String jsonString) {
  return json.decode(jsonString);
}

void main() {
  Map<String, String> data = {"hello": "world"};
  String jsonString = toJson(data);
  data = fromJson(jsonString);
  print(data);
}

当我运行它时,它会失败;

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

on this online editor失败,并显示另一个错误;

Uncaught exception:
TypeError: Instance of '_JsonMap': type '_JsonMap' is not a subtype of type 'Map<String, String>'

1 个答案:

答案 0 :(得分:0)

解决方法,

我不喜欢它,但是可以解决该问题。将fromJson函数返回的值与Map<String, String>.from(...)

换行

例如:

void main() {
  Map<String, String> data = {"hello": "world"};
  String jsonString = toJson(data);
  data = Map<String, String>.from(fromJson(jsonString));
  print(data);
}