Flutter - Json array of objects

12,778

Follor this url you will more idea about json parse. https://medium.com/flutter-community/parsing-complex-json-in-flutter-747c46655f51

Here is the code that what exectly you looking, i have use with static json in assets so you have to replace with your resonse.

    import 'dart:async' show Future;
    import 'package:flutter/services.dart' show rootBundle;
    import 'dart:convert';
    import 'package:flutter_json/model/location_model.dart';

    Future<String> _loadlocationAsset() async {
    return await rootBundle.loadString('assets/location.json');
    }

    Future loadLocation() async {
    String jsonLocation = await _loadlocationAsset();
    final jsonResponse = json.decode(jsonLocation);
    LocationData location = new LocationData.fromJson(jsonResponse);
    print(location.data[0].name);
    }

Data model

     class LocationData {
        final int code;
        final String status;
        final String message;
        final List<Data> data;

        LocationData({this.code, this.status,this.message, this.data});

        factory LocationData.fromJson(Map<String, dynamic> parsedJson){

            var list = parsedJson['data'] as List;
            print(list.runtimeType);
            List<Data> dataList = list.map((i) => Data.fromJson(i)).toList();


            return LocationData(
                code: parsedJson['code'],
                status: parsedJson['status'],
                message: parsedJson['message'],
                data: dataList
            );
        }
        }

        class Data {
        final int id;
        final int parent;
        final String name;
        final String type;
        final String imageURL;

        Data({this.id, this.parent,this.name,this.type,this.imageURL});

        factory Data.fromJson(Map<String, dynamic> parsedJson){
            return Data(
                id:parsedJson['id'],
                parent:parsedJson['parent'],
                name:parsedJson['name'],
                type:parsedJson['type'],
                imageURL:parsedJson['imageURL']
            );
        }
        }
Share:
12,778
Bollie
Author by

Bollie

Updated on June 20, 2022

Comments

  • Bollie
    Bollie almost 2 years

    How would I parse a nested array of objects such as the one below.

    {
        "status": "success",
        "code": 200,
        "message": "The request was successful",
        "data": [
            {
                "name": "Abu Dhabi",
                "id": 4139,
                "parent": 5153,
                "type": "city",
                "imageURL": ""
    
            },
            {
                "name": "Croatia",
                "id": 5037,
                "parent": 6886,
                "type": "country",
                "imageURL": ""
    
            },
         ]
    }
    

    I am currently making an API call which returns data in the format as shown above.

    My api call is as follows:

      Future<Location> getLocations() async {
        final response =
            await http.get('$endpoint/locations', headers: authenticatedHeader);
    
        if (response.statusCode == 200) {
          final responseJson = json.decode(response.body);
    
          // If server returns an OK response, parse the JSON.
    
          return Location.fromJson(responseJson);
        } else {
          // If that response was not OK, throw an error.
          throw Exception('Failed to load post');
        }
      }
    

    I then have a location class as below:

    class Location {
      String name;
      int id;
      int parent;
      String type;
      String imageURL;
    
      Location(
          {this.name, this.id, this.parent, this.type, this.imageURL});
    
      factory Location.fromJson(Map<String, dynamic> json) =>
          _locationFromJson(json);
    }
    
    Location _locationFromJson(Map<String, dynamic> json) {
      return Location(
        name: json['name'] as String,
        id: json['id'] as int,
        parent: json['parent'] as int,
        type: json['type'] as String,
        imageURL: json['imageURL'] as String
      );
    }
    

    I am hoping to be able to retrieve all the locations above using a listview builder and create a listtile for each location.

    How can I parse the JSON correctly?