[英]Unhandled Exception: type 'String' is not a subtype of type 'Map<String, dynamic> flutter
[英]Flutter/Dart Unhandled Exception: type 'String' is not a subtype of type 'Map<String, dynamic>' in type cast
我正在将 JSON 作为字符串从 response.body 发送,但在 Flutter/Dart 中映射后得到“未处理的异常:类型 'String' 不是类型转换中的类型 'Map<String, dynamic>' 的子类型”错误。 如果我手动编写 JSON,则代码有效。 但是,如果我从参数中获取 JSON 作为字符串,则会出现转换错误。
我试图将返回值转换为 List 但我猜提取的数据应该改变,卡在这里。 “s”是 JSON 字符串。
getVacDates 函数仅用于通过映射从 JSON 中获取日期或总值,例如[10/14/21, 10/15/21, 10/16/21...]
。
static List<String> getVacDates(String s) {
final newList = jsonEncode(s);
final extractedData = jsonDecode(newList) as Map<String, dynamic>;
final china= extractedData['timeline'].map((e) => e["date"]);
List<String> StringList = china.cast<String>();
print(StringList);
return StringList;
}
有关信息,JSON 是:
{"country":"USA","timeline":
[{"total":409571117,"daily":757824,"totalPerHundred":121,"dailyPerMillion":2253,"date":"10/14/21"},
{"total":410559043,"daily":743873,"totalPerHundred":122,"dailyPerMillion":2212,"date":"10/15/21"},
{"total":411028977,"daily":737439,"totalPerHundred":122,"dailyPerMillion":2193,"date":"10/16/21"},
{"total":411287235,"daily":731383,"totalPerHundred":122,"dailyPerMillion":2175,"date":"10/17/21"}]}
不完全确定你想要得到什么,但它是这样的吗?
import 'dart:convert';
void main() {
print(getVacDates(jsonString)); // [10/14/21, 10/15/21, 10/16/21, 10/17/21]
}
List<String> getVacDates(String s) => [
for (final timeline in jsonDecode(s)['timeline'])
timeline['date'] as String
];
const jsonString = '''{
"country": "USA",
"timeline": [
{
"total": 409571117,
"daily": 757824,
"totalPerHundred": 121,
"dailyPerMillion": 2253,
"date": "10/14/21"
},
{
"total": 410559043,
"daily": 743873,
"totalPerHundred": 122,
"dailyPerMillion": 2212,
"date": "10/15/21"
},
{
"total": 411028977,
"daily": 737439,
"totalPerHundred": 122,
"dailyPerMillion": 2193,
"date": "10/16/21"
},
{
"total": 411287235,
"daily": 731383,
"totalPerHundred": 122,
"dailyPerMillion": 2175,
"date": "10/17/21"
}
]
}''';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.