将json转换为Map <string,map <string,string >>格式

时间:2019-04-25 09:55:45

标签: dart flutter

我需要将json字符串转换为嵌套Map并进行访问。

下面的Json String是下面给出的Map形式

Map<String,Map<String,String>> 

{"0":{"1551874690005":"2","1551874722124":"2","1551874810817":"2","1551874681110":"2","1551874739821":"2","1551874763604":"2","1551874692381":"2","1551874816028":"2","1551874708292":"2","1551874804308":"2","1551874694205":"2","1551874696644":"2","1551874729332":"2","1551874749950":"2","1551874767786":"2"},"1":{"1551948649643":"0","1551948733576":"0","1551948601167":"0","1551948592816":"0","1551948699297":"0","1551874822043":"2","1551948681513":"0","1551948531568":"0","1551948577374":"0","1551948719758":"0","1552370125650":"0","1551948549863":"0","1551948564519":"0","1551948631000":"0","1551953956716":"0"},"2":{"1551875011432":"0","1551875020618":"0","1551874991952":"0","1551875091300":"0","1551875073622":"0","1551875032851":"0","1551874827691":"0","1551948658122":"0","1551874846523":"0","null":"0","1552545417127":"0","1551875083856":"0","1551874929076":"0","1552545972738":"0"},"3":{"1552651031695":"0"},"4":{"1551875144268":"0","1551875157028":"0","1551875115211":"0","1551875124660":"0"}}

尝试使用我的代码时出现以下错误:

Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Map<String, String>' in type cast
Map offlineExeStatus = jsonDecode(prefs.getString("offlineExeStatus"));

Map<String,Map<String,String>> exeStatusFinalJson = new Map();

exeStatusFinalJson = offlineExeStatus.cast<String,Map<String,String>();

需要在“ exeStatusFinalJson”地图中强制转换给定的json并进行如下访问: exeStatusFinalJson [“ 0”]应该提供如下输出:

{"1551874690005":"2","1551874722124":"2","1551874810817":"2","1551874681110":"2","1551874739821":"2","1551874763604":"2","1551874692381":"2","1551874816028":"2","1551874708292":"2","1551874804308":"2","1551874694205":"2","1551874696644":"2","1551874729332":"2","1551874749950":"2","1551874767786":"2"}

2 个答案:

答案 0 :(得分:0)

尝试将地图声明为Map<String, dynamic>,而不是Map<String, Map<String, String>>

答案 1 :(得分:0)

最后想出了办法!

Map offlineExeStatus = jsonDecode(prefs.getString("onlineExeStatus"));

Map<String, dynamic> exeStatusJson = new Map();

Map<String, Map<String, String>> exeStatusFinalJson = new Map();

List<String> mapKeyExe = new List();

mapKeyExe = offlineExeStatus.keys.cast<String>().toList();

exeStatusJson = offlineExeStatus.cast<String, dynamic>();

for (int i = 0; i < mapKeyExe.length; i++) {
    Map<String, String> exeStatusInsideJson = new Map();

    exeStatusInsideJson = offlineExeStatus[mapKeyExe[i].toString()]
       .cast<String, String>();

    exeStatusFinalJson[i.toString()] = exeStatusInsideJson;

    print(exeStatusFinalJson);
}