我正在尝试从下面的JSON格式中获取数组中的City
和Counter
。
{
"responseCode": 200,
"responseBody": {
"success": [
{
"city": "C1",
"counters": [
"S1",
"S2",
"S3",
"S4",
"S5"
]
},
{
"city": "C2",
"counters": [
"S6",
"S7",
"S8",
"S9",
"S10"
]
}
]
}
}
我已经写了代码从API中获取JSON,但无法这样做。
我写了下面的代码来检索JSON。
Future<Map<String, dynamic>> fetchCityCounterDetail(int id) async {
final url = 'myapi_url';
final response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
final data = json.decode(response.body);
print(data);
print(data["responseBody"]["success"]);
print(data["responseBody"]["success"]["city"]);
return data;
} else {
throw Exception('Failed to fetch city counter detail');
}
}
1条答案
按热度按时间xqkwcwgp1#
您必须创建一个
Model
类,然后正确地获取数据。示例型号:
然后更新
future
函数如下:在其他地方,您可以将其用作: