英文:
How to properly fetch json object which contains array in flutter
问题
我正在尝试从以下 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');
}
}
请注意,你的代码中有一个问题,即 print(data["responseBody"]["success"]["city"]);
这一行会导致错误,因为 "success" 是一个数组,你需要遍历数组中的元素才能获取每个元素的 "city" 属性。
英文:
I am trying the get City
and Counter
in Arrays from below json format.
{
"responseCode": 200,
"responseBody": {
"success": [
{
"city": "C1",
"counters": [
"S1",
"S2",
"S3",
"S4",
"S5"
]
},
{
"city": "C2",
"counters": [
"S6",
"S7",
"S8",
"S9",
"S10"
]
}
]
}
}
I have written the code to get the json from API but not able to do so.
I have written below code to retrieve the 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
得分: 2
你需要创建一个Model
类,并正确获取数据。
示例Model:
class Model {
String? city;
List<String>? counters;
Model({this.city, this.counters});
Model.fromJson(Map<String, dynamic> json) {
city = json['city'];
counters = json['counters'].cast<String>();
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['city'] = this.city;
data['counters'] = this.counters;
return data;
}
}
然后,你可以更新你的future
函数如下:
Future<List<Model>> fetchCityCounterDetail() async {
final url = 'myapi_url';
final response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
final data = json.decode(response.body);
final successData = data["success"];
List<Model> models = [];
for (var i = 0; i < successData.length; i++) {
final city = successData[i]["city"];
final counters = successData[i]["counters"].cast<String>();
models.add(Model(city: city, counters: counters));
}
return models;
} else {
throw Exception('Failed to fetch city counter detail');
}
}
然后,你可以在其他地方使用它,如下所示:
final models = await fetchCityCounterDetail();
for (var i = 0; i < models.length; i++) {
final model = models[i];
print("City: ${model.city}");
print("Counters: ${model.counters}");
}
英文:
You have to create a Model
class and then properly fetch the data.
Example Model:
class Model {
String? city;
List<String>? counters;
Model({this.city, this.counters});
Model.fromJson(Map<String, dynamic> json) {
city = json['city'];
counters = json['counters'].cast<String>();
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['city'] = this.city;
data['counters'] = this.counters;
return data;
}
}
And then your update your future
function like:
Future<List<Model>> fetchCityCounterDetail() async {
final url = 'myapi_url';
final response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
final data = json.decode(response.body);
final successData = data["success"];
List<Model> models = [];
for (var i = 0; i < successData.length; i++) {
final city = successData[i]["city"];
final counters = successData[i]["counters"].cast<String>();
models.add(Model(city: city, counters: counters));
}
return models;
} else {
throw Exception('Failed to fetch city counter detail');
}
}
And else where you can use it as:
final models = await fetchCityCounterDetail();
for (var i = 0; i < models.length; i++) {
final model = models[i];
print("City: ${model.city}");
print("Counters: ${model.counters}");
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论