我将如何转换此地图
{
"country": "uk",
"postcode": "500",
"suburbs": [
{
"code": "liverpool",
"name": "liverpool"
},
{
"code": "merseyside",
"name": "merseyside"
}
]
}
到
{
"country": "uk",
"postcode": "500",
"suburb":"liverpool"
}
答案 0 :(得分:1)
我想您首先自己尝试过,但是由于地图包含不同类型的元素而导致类型问题。
您可以通过编译器知道类型为dynamic
(禁用类型安全性)的方式声明Map:
void main() async {
final mapFrom = <String, dynamic>{
"country": "uk",
"postcode": "500",
"suburbs": [
{"code": "liverpool", "name": "liverpool"},
{"code": "merseyside", "name": "merseyside"}
]
};
final mapTo = {
"country": mapFrom["country"],
"postcode": mapFrom["country"],
"suburbs": mapFrom["suburbs"][0]["code"]
};
print(mapTo); // {country: uk, postcode: uk, suburbs: liverpool}
}
如果要修改地图,请执行以下操作:
final mapTo = Map.of(mapFrom);
mapTo["suburbs"] = mapTo["suburbs"][0]["code"];