Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to parse complex json in flutter

I have trouble getting data from a complex json, below is the json in the request.

{
   "results":{
      "TotalRecordCount":"1",
      "Records":[
         {
            "code":"PCK_34333338365C93E2D50DB9C",
            "address":"1 AV KHEIREDDINE PACHA Imm Pacha centre BLOC B tunis Tunis 1000",
            "contact_phone":"99608258"
         }
      ],
      "Result":"OK"
   }
}

Below is the model I made.

import 'dart:convert';

class Pickup {
  String status;
  List message;
  //Map<String ,dynamic> results;
  Results results;
  Pickup(
    {this.status,
     this.message,
     this.results,
  });
  factory Pickup.fromJson(Map<String, dynamic> json) {
    return Pickup(
             status: json["status"] as String,
             results: Results.fromJson(json["results"]),

           );
  }
}

class Results {
  String TotalRecordCount;
  records Records;

  Results({this.TotalRecordCount,this.Records});

  factory Results.fromJson(Map<String, dynamic> json) {
    return Results(
    TotalRecordCount: json["TotalRecordCount"],
    Records:records.fromJson(json["Records"]),

    );
  }
}

class records{
  String code;
  String address;
  String contact_phone;

  records({
    this.code,
    this.address,
    this.contact_phone
  });

  factory records.fromJson(Map<String, dynamic> json) {
    return records(
      code: json["code"],
      address: json["address"],
      contact_phone: json["contact_phone"],
    );
  }
}

Now Im trying to parse the records to get the code or address and print it.

if (response.statusCode == 200) {
  print(response.body);
  final responseJson = json.decode(response.body);
  var da=Pickup.fromJson(responseJson);
  Results dat=da.results;
  records data=dat.Records;
  print(data.address);
}

The response.body is working fine but when I try to parse results or records I got 'List' is not a subtype of type 'Map<String, dynamic>' error

like image 911
killuazoldayeck Avatar asked Apr 16 '19 14:04

killuazoldayeck


People also ask

How do you decode a list of JSON in flutter?

To decode a JSON string the json_serializable way, you do not have actually to make any changes to our previous code. Map<String, dynamic> userMap = jsonDecode(jsonString); var user = User.fromJson(userMap);

How do you use toJson in flutter?

We have 3 steps to convert an Object/List to JSON string: create the class. create toJson() method which returns a JSON object that has key/value pairs corresponding to all fields of the class. get JSON string from JSON object/List using jsonEncode() function.


2 Answers

I will definitely recommend you this website json to dart App Quicktype just don't forget to select Dart in the right side.

You just put your json in la left and in will give you something like this:

// To parse this JSON data, do
//
//     final pickUp = pickUpFromJson(jsonString);

import 'dart:convert';

PickUp pickUpFromJson(String str) => PickUp.fromJson(json.decode(str));

String pickUpToJson(PickUp data) => json.encode(data.toJson());

class PickUp {
    Results results;

    PickUp({
        this.results,
    });

    factory PickUp.fromJson(Map<String, dynamic> json) => new PickUp(
        results: Results.fromJson(json["results"]),
    );

    Map<String, dynamic> toJson() => {
        "results": results.toJson(),
    };
}

class Results {
    String totalRecordCount;
    List<Record> records;
    String result;

    Results({
        this.totalRecordCount,
        this.records,
        this.result,
    });

    factory Results.fromJson(Map<String, dynamic> json) => new Results(
        totalRecordCount: json["TotalRecordCount"],
        records: new List<Record>.from(json["Records"].map((x) => Record.fromJson(x))),
        result: json["Result"],
    );

    Map<String, dynamic> toJson() => {
        "TotalRecordCount": totalRecordCount,
        "Records": new List<dynamic>.from(records.map((x) => x.toJson())),
        "Result": result,
    };
}

class Record {
    String code;
    String address;
    String contactPhone;

    Record({
        this.code,
        this.address,
        this.contactPhone,
    });

    factory Record.fromJson(Map<String, dynamic> json) => new Record(
        code: json["code"],
        address: json["address"],
        contactPhone: json["contact_phone"],
    );

    Map<String, dynamic> toJson() => {
        "code": code,
        "address": address,
        "contact_phone": contactPhone,
    };
}

at the beginning it will tell you how you can use it.

// To parse this JSON data, do
//
//     final pickUp = pickUpFromJson(jsonString);

So when you call it in you code its gonna be something like this.

  Future<Pickup> getPickup() async {
    var response = await http.get(url);
    return pickUpFromJson(response.body);
  }

This code could be call for a FutureBuilder for example or wherever you set the code to wait for a future.

like image 198
Argel Bejarano Avatar answered Oct 06 '22 21:10

Argel Bejarano


Try this: https://flutter.dev/docs/development/data-and-backend/json#serializing-json-using-code-generation-libraries

Specifically the part that uses json_serializable

like image 20
Nomnom Avatar answered Oct 06 '22 20:10

Nomnom