Extract Data from JSON Array in Flutter/Dart

Viewed 8053

This is the response from request.

var response = [{"id":4731},{"id":4566},{"id":4336},{"id":4333},{"id":4172},{"id":4170},{"id":4168},{"id":4166},{"id":4163},{"id":4161}];

How to extract ids and store in List of int using flutter. I have try this code but not working.

Future<List<int>> fetchTopIds() async{

     final response = await client.get('$_baseUrl/posts?fields=id');
     final ids = json.decode(response.body); 
     return ids.cast<int>();
}
4 Answers

This should do what you want:

var intIds = ids.map<int>((m) => m['id'] as int).toList();

This is what I did when got "array of object" as response (I know I'm late. But it will help the next guy)

    List list = json.decode(response.body);

  if (response.body.contains("id")) {
    var lst = new List(list.length);

    for (int i = 0; i < list.length; i++) {
      var idValue = list[i]['id'];
      print(idValuee);
    }

Here I attached a complete example of converting a list to JSON and then retrieve the List back from that JSON.

import 'dart:convert';

void main() {

  List<int> a= [1,2,3]; //List of Integer

  var json= jsonEncode(a); //json Encoded to String
  print(json.runtimeType.toString());

  var dec= jsonDecode(json); //Json Decoded to array of dynamic object

  print(dec.runtimeType.toString());


  a= (dec as List).map((t)=> t as int).toList(); //dynamic array mapped to integer List

  print(a);
}

I found a better and easier way to get required information/ data from JSON Array.

Refer to https://pub.dev/packages/http/example to know more

Code to get a quick starts:

void main(List<String> arguments) async {
var url = 'ENTER YOUR API ENDPOINT';
var response = await http.get(url);
var jsonResponse = convert.jsonDecode(response.body);
var itemCount = jsonResponse['totalItems'];
print('Number of books about http: $itemCount.');

Here 'totalItems' would be your desired key.This will only work if you get a response.statusCode == 200

Related