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

huangapple go评论59阅读模式
英文:

How to properly fetch json object which contains array in flutter

问题

我正在尝试从以下 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');
    }
}

请注意,你的代码中有一个问题,即 print(data["responseBody"]["success"]["city"]); 这一行会导致错误,因为 "success" 是一个数组,你需要遍历数组中的元素才能获取每个元素的 "city" 属性。

英文:

I am trying the get City and Counter in Arrays from below json format.

{
&quot;responseCode&quot;: 200,
&quot;responseBody&quot;: {
    &quot;success&quot;: [
        {
            &quot;city&quot;: &quot;C1&quot;,
            &quot;counters&quot;: [
                &quot;S1&quot;,
                &quot;S2&quot;,
                &quot;S3&quot;,
                &quot;S4&quot;,
                &quot;S5&quot;
            ]
        },
        {
            &quot;city&quot;: &quot;C2&quot;,
            &quot;counters&quot;: [
                &quot;S6&quot;,
                &quot;S7&quot;,
                &quot;S8&quot;,
                &quot;S9&quot;,
                &quot;S10&quot;
            ]
        }
    ]
}

}

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&lt;Map&lt;String, dynamic&gt;&gt; fetchCityCounterDetail(int id) async {
  final url = &#39;myapi_url&#39;;

  final response = await http.get(Uri.parse(url));

  if (response.statusCode == 200) {
    final data = json.decode(response.body);
    print(data);
    print(data[&quot;responseBody&quot;][&quot;success&quot;]);
    print(data[&quot;responseBody&quot;][&quot;success&quot;][&quot;city&quot;]);

    return data;
  } else {
    throw Exception(&#39;Failed to fetch city counter detail&#39;);
  }
}

答案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&lt;String&gt;? counters;

  Model({this.city, this.counters});

  Model.fromJson(Map&lt;String, dynamic&gt; json) {
    city = json[&#39;city&#39;];
    counters = json[&#39;counters&#39;].cast&lt;String&gt;();
  }

  Map&lt;String, dynamic&gt; toJson() {
    final Map&lt;String, dynamic&gt; data = new Map&lt;String, dynamic&gt;();
    data[&#39;city&#39;] = this.city;
    data[&#39;counters&#39;] = this.counters;
    return data;
  }
}

And then your update your future function like:

Future&lt;List&lt;Model&gt;&gt; fetchCityCounterDetail() async {
  final url = &#39;myapi_url&#39;;
  final response = await http.get(Uri.parse(url));

  if (response.statusCode == 200) {
    final data = json.decode(response.body);
    final successData = data[&quot;success&quot;];

    List&lt;Model&gt; models = [];
    for (var i = 0; i &lt; successData.length; i++) {
      final city = successData[i][&quot;city&quot;];
      final counters = successData[i][&quot;counters&quot;].cast&lt;String&gt;();

      models.add(Model(city: city, counters: counters));
    }

    return models;
  } else {
    throw Exception(&#39;Failed to fetch city counter detail&#39;);
  }
}

And else where you can use it as:

final models = await fetchCityCounterDetail();
for (var i = 0; i &lt; models.length; i++) {
  final model = models[i];
  print(&quot;City: ${model.city}&quot;);
  print(&quot;Counters: ${model.counters}&quot;);
}

huangapple
  • 本文由 发表于 2023年3月31日 16:56:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/75896615.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定