How to convert json data into array in Flutter

0 votes

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

 

Mar 31, 2023 in Flutter by Ashwini
• 5,430 points
12,637 views

1 answer to this question.

0 votes

To convert the JSON data into an array in Flutter, you can use the json.decode function to convert the JSON string into a map, and then access the array using the keys and indexes.

Here's an example of how you can get the cities and counters as arrays from your JSON data:

Future<List<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);

    final List<dynamic> successList = data["responseBody"]["success"];

    final List<Map<String, dynamic>> citiesAndCounters = [];

    successList.forEach((success) {
      final Map<String, dynamic> cityAndCounters = {
        "city": success["city"],
        "counters": success["counters"],
      };

      citiesAndCounters.add(cityAndCounters);
    });

    return citiesAndCounters;
  } else {
    throw Exception('Failed to fetch city counter detail');
  }
}

In the above example, the json.decode function is used to decode the JSON data into a map. Then, the success list is accessed using the key responseBody.success. A new list, citiesAndCounters, is initialized to store the city and counter data.

A forEach loop is used to iterate over each object in the success list. For each object, a new map is created with the city and counters values, and added to the citiesAndCounters list.

Finally, the citiesAndCounters list is returned as the result.

You can then use this function to retrieve the city and counter data as an array, and use it to populate your UI.

To know more, join our Flutter Course today.

answered Mar 31, 2023 by seena

Related Questions In Flutter

0 votes
1 answer

How to Deserialize a list of objects from json in flutter Ask Question?

To deserialize a list of objects from ...READ MORE

answered Mar 28, 2023 in Flutter by vishalini
2,281 views
0 votes
1 answer

How to change Android minSdkVersion in Flutter Project?

Yes, you can change the minSdkVersion in ...READ MORE

answered Mar 21, 2023 in Flutter by Tej
11,084 views
0 votes
1 answer

How to implement drop down list in flutter?

You're close! The error you're getting is ...READ MORE

answered Mar 26, 2023 in Flutter by vishalini
4,083 views
0 votes
2 answers

How to create a circle icon button in Flutter?

To create something similar to a FloatingActionButton, ...READ MORE

answered Aug 23, 2023 in Flutter by anonymous
• 140 points
14,351 views
0 votes
0 answers

json_decode to array

I want to decode a JSON string ...READ MORE

Jun 3, 2022 in PHP by Kichu
• 19,040 points
1,076 views
0 votes
0 answers

PHP Array to JSON Array using json_encode();

I have encoded an Array I've made using ...READ MORE

Jun 13, 2022 in PHP by narikkadan
• 63,600 points
662 views
0 votes
0 answers

jQuery JSON Decode ( PHP to Javascript)

I'm trying to make an autocomplete script. ...READ MORE

Jul 1, 2022 in Web Development by gaurav
• 23,260 points
568 views
0 votes
1 answer

Can't able fetch data form json using class in flutter(dart)

To fix the issue of null temperature ...READ MORE

answered Mar 18, 2023 in Android by vinayak
1,351 views
0 votes
1 answer

How to dynamically resize text in Flutter?

You can use the FittedBox widget to ...READ MORE

answered Mar 27, 2023 in Flutter by Tej
8,927 views
0 votes
1 answer

How to present an empty view in flutter?

In Flutter, you can present an empty ...READ MORE

answered Mar 27, 2023 in Flutter by anonymous
4,582 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP