如何正确获取Flutter中包含数组的JSON对象

cuxqih21  于 2023-03-31  发布在  Flutter
关注(0)|答案(1)|浏览(135)

我正在尝试从下面的JSON格式中获取数组中的CityCounter

{
"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');
  }
}
xqkwcwgp

xqkwcwgp1#

您必须创建一个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}");
}

相关问题