简体   繁体   中英

flutter get json array

Hi I have this JSON as a string as a response for an API call

{
    "friends": {
        "data": [],
        "summary": {
            "total_count": 42
        }
    },
    "id": "111111111111111"
}

I want to get friends.data and friends.summary.total_count . Something like:

for (int i = 0 ; i < friends.summary.total_count ; i++)
{
    myAmazingArray.pushback(friends.data[i]);
}

I think that total_count is the number of contents in the array. I also know that in order to get the "id" I have to do: json['name']

You need to use jsonDecode from dart:convert. Actually you don't even need to use the total_count value at all, if the length in data is the same. You can simply use:

 import 'dart:convert';

 final Map<String, dynamic> dataMap = jsonDecode(json);
 final List<dynamic> friendsData = dataMap['friends']['data'];

 for(dynamic friend in friendsData) myAmazingArray.pushback(friend);

I don't know what kind of content is contained in data , so I suggest you to find out the runtime type (eg String, Map etc.) and exchange the word 'dynamic' in my code above to improve the code quality.

If you wanted to do it with total_count:

final int total_count = dataMap['friends']['summary']['total_count'];

for(int i=0; i<total_count; i++)
    myAmazingArray.pushback(friendsData[i]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM