skip to Main Content

When i called getall endpoint, its gives me to like below json object and I’m gonna bind that value to a Entity class.But cant assign new values or access response value.Because it have inside the another json object.I will attach that codes below.

I want to know the correct order of create a entity that json object have several object for json object id in flutter

[
    {
        "id": "931992ff-6ec6-43c9-a54c-b1c5601d58e5",
        "sp_id": "062700016",
        "phone_number": "+94716035826",
        "nic": "991040293V",
        "**drivers_license**": {
            "license_id": "12345678",
            "expiry_date": "2023-09-36"
        },
        "user_level": "",
        "gender": "Male",
        "user_sub_type": "app_user",
        "is_fleet_owner": false,
        "fleet_id": "",
        "documents": null,
        "payment_parameters": {
            "account_holder_name": "",
            "bank_name": "",
            "branch_name": "",
            "account_number": "",
            "swift_code": ""
        }
    }
]

I want to create the entity which is bolded in the json calling "drivers_license" object

I tried entity class like thi.,But can’t get proper understand how to implement like part of drivers_license above json.

class ServiceProviderModel {
  String id = "";
  String phone_number = "";
  String nic = "";
  String license_id = "";
  String expiry_date = "";
  String gender = "";
  String user_sub_type = "";
  String document_type_1 = "";
  String document_type_2 = "";
  String first_name = "";
  String last_name = "";
  String email = "";
  String profile_pic_url = "";
  String emergency_contact = "";
  String status = "active";

  ServiceProviderModel();

  ServiceProviderModel.fromJson(Map json)
      : id = json['id'],
        phone_number = json['phone_number'],
        nic = json['nic'],
        license_id = json['license_id'],
        gender = json['gender'],
        user_sub_type = json['user_sub_type'],
        document_type_1 = json['document_type_1'],
        document_type_2 = json['document_type_2'],
        first_name = json['first_name'],
        last_name = json['last_name'],
        email = json['email'],
        profile_pic_url = json['profile_pic_url'],
        emergency_contact = json['emergency_contact'],
        expiry_date = json['expiry_date'],
        status = json['status'];

  Map toJson() => {
        'id': id,
        'phone_number': phone_number,
        'nic': nic,
        'license_id': license_id,
        'gender': gender,
        'user_sub_type': user_sub_type,
        'document_type_1': document_type_1,
        'document_type_2': document_type_2,
        'first_name': first_name,
        'last_name': last_name,
        'email': email,
        'profile_pic_url': profile_pic_url,
        'emergency_contact': emergency_contact,
        'expiry_date': expiry_date,
        'status': status,
      };
}

4

Answers


  1. Chosen as BEST ANSWER

    I found a good answer for this question, and I used the below code to solve this issue. This is very simple and clean

    class ServiceProviderModel {
      String id = "";
      String phone_number = "";
      String nic = "";
      Map drivers_license = new Map();
      String license_id = "";
      String expiry_date = "";
      String gender = "";
      String user_sub_type = "";
      Map documents = new Map();
      String document_type_1 = "";
      String document_type_2 = "";
      String first_name = "";
      String last_name = "";
      String email = "";
      String profile_pic_url = "";
      String emergency_contact = "";
      String status = "active";
    
      ServiceProviderModel();
    
      ServiceProviderModel.fromJson(Map json)
          : id = json['id'],
            phone_number = json['phone_number'],
            nic = json['nic'],
            drivers_license = json['drivers_license'],
            gender = json['gender'],
            user_sub_type = json['user_sub_type'],
            documents = json['documents'],
            first_name = json['first_name'],
            last_name = json['last_name'],
            email = json['email'],
            profile_pic_url = json['profile_pic_url'],
            emergency_contact = json['emergency_contact'],
            status = json['status'];
    
      Map toJson() =>
          {
            'id': id,
            'phone_number': phone_number,
            'nic': nic,
            'drivers_license': drivers_license,
            'gender': gender,
            'user_sub_type': user_sub_type,
            'documents': documents,
            'first_name': first_name,
            'last_name': last_name,
            'email': email,
            'profile_pic_url': profile_pic_url,
            'emergency_contact': emergency_contact,
            'status': status,
          };
    }
    

  2. Typically you create a new class for your child entities with properties, with there own from and to json methods. Then call those methods in your fromJson methods of the parent class.

    classe DriversLicense {
        final String license_id;
        final String expiry_date;
    
        factory Post.fromJson(Map<String, dynamic> json) {
        return DriversLicense(
          license_id: json['id'],
          expiry_date: json['expiry_date'] ?? ""
        );
      }
    }
    

    Psudeo code for you to insert.

    class ServiceProviderModel {
    ...
    DriversLicense drivers_license;
    ...
    
    ServiceProviderModel.fromJson(Map json)
          : id = json['id'],
          ...
          drivers_license = DriversLicense.fromJson(json['license_id']),
          ...
    

    Heres a more complete example from my own project. This sets the classes as immutable and provides a copyWith method for applying changes to a new instance. Doesn’t include the toJson() but thats the same as you currently have in terms of structure pretty much.

    import 'package:lon_flutter_poc_app/data/graphql/gen/author.dart';
    
    // THIS IS GENERATED BY CODE. YOU WILL LOOSE MANUAL CHANGES!
    class Post {
      final int id;
      final String title;
      final Author author;
      final int votes;
    
      Post({required this.id, required this.title, required this.author, required this.votes});
    
      // THIS IS GENERATED BY CODE. YOU WILL LOOSE MANUAL CHANGES!
    
      factory Post.fromJson(Map<String, dynamic> json) {
        return Post(
          id: json['id'],
          title: json['title'] ?? "",
          author: Author.fromJson(json['author'] ?? {}),
          votes: json['votes'],
        );
      }
    
      // THIS IS GENERATED BY CODE. YOU WILL LOOSE MANUAL CHANGES!
      Post copyWith({
        int? id,
        String? title,
        Author? author,
        int? votes,
      }) {
        return Post(
          id: id ?? this.id,
          title: title ?? this.title,
          author: author ?? this.author,
          votes: votes ?? this.votes,
        );
      }
    }
    
    
    import 'package:lon_flutter_poc_app/data/graphql/gen/post.dart';
    
    // THIS IS GENERATED BY CODE. YOU WILL LOOSE MANUAL CHANGES!
    class Author {
      final int id;
      final String firstName;
      final String lastName;
    
      Author({required this.id, required this.firstName, required this.lastName});
    
      // THIS IS GENERATED BY CODE. YOU WILL LOOSE MANUAL CHANGES!
    
      factory Author.fromJson(Map<String, dynamic> json) {
    
        return Author(
          id: json['id'],
          firstName: json['firstName'] ?? "",
          lastName: json['lastName'] ?? ""
        );
      }
    
      // THIS IS GENERATED BY CODE. YOU WILL LOOSE MANUAL CHANGES!
      Author copyWith({
        int? id,
        String? firstName,
        String? lastName,
      }) {
        return Author(
          id: id ?? this.id,
          firstName: firstName ?? this.firstName,
          lastName: lastName ?? this.lastName
        );
      }
    }
    
    
    Login or Signup to reply.
  3. I suggest using a tool like https://app.quicktype.io/.
    Entering your example JSON can generate this for example

    import 'dart:convert';
    
    class ServiceProviderModel {
        String id;
        String spId;
        String phoneNumber;
        String nic;
        DriversLicense driversLicense;
        String userLevel;
        String gender;
        String userSubType;
        bool isFleetOwner;
        String fleetId;
        dynamic documents;
        PaymentParameters paymentParameters;
    
        ServiceProviderModel({
            required this.id,
            required this.spId,
            required this.phoneNumber,
            required this.nic,
            required this.driversLicense,
            required this.userLevel,
            required this.gender,
            required this.userSubType,
            required this.isFleetOwner,
            required this.fleetId,
            this.documents,
            required this.paymentParameters,
        });
    
        factory ServiceProviderModel.fromJson(String str) => ServiceProviderModel.fromMap(json.decode(str));
    
        String toJson() => json.encode(toMap());
    
        factory ServiceProviderModel.fromMap(Map<String, dynamic> json) => ServiceProviderModel(
            id: json["id"],
            spId: json["sp_id"],
            phoneNumber: json["phone_number"],
            nic: json["nic"],
            driversLicense: DriversLicense.fromMap(json["drivers_license"]),
            userLevel: json["user_level"],
            gender: json["gender"],
            userSubType: json["user_sub_type"],
            isFleetOwner: json["is_fleet_owner"],
            fleetId: json["fleet_id"],
            documents: json["documents"],
            paymentParameters: PaymentParameters.fromMap(json["payment_parameters"]),
        );
    
        Map<String, dynamic> toMap() => {
            "id": id,
            "sp_id": spId,
            "phone_number": phoneNumber,
            "nic": nic,
            "drivers_license": driversLicense.toMap(),
            "user_level": userLevel,
            "gender": gender,
            "user_sub_type": userSubType,
            "is_fleet_owner": isFleetOwner,
            "fleet_id": fleetId,
            "documents": documents,
            "payment_parameters": paymentParameters.toMap(),
        };
    }
    
    class DriversLicense {
        String licenseId;
        String expiryDate;
    
        DriversLicense({
            required this.licenseId,
            required this.expiryDate,
        });
    
        factory DriversLicense.fromJson(String str) => DriversLicense.fromMap(json.decode(str));
    
        String toJson() => json.encode(toMap());
    
        factory DriversLicense.fromMap(Map<String, dynamic> json) => DriversLicense(
            licenseId: json["license_id"],
            expiryDate: json["expiry_date"],
        );
    
        Map<String, dynamic> toMap() => {
            "license_id": licenseId,
            "expiry_date": expiryDate,
        };
    }
    
    class PaymentParameters {
        String accountHolderName;
        String bankName;
        String branchName;
        String accountNumber;
        String swiftCode;
    
        PaymentParameters({
            required this.accountHolderName,
            required this.bankName,
            required this.branchName,
            required this.accountNumber,
            required this.swiftCode,
        });
    
        factory PaymentParameters.fromJson(String str) => PaymentParameters.fromMap(json.decode(str));
    
        String toJson() => json.encode(toMap());
    
        factory PaymentParameters.fromMap(Map<String, dynamic> json) => PaymentParameters(
            accountHolderName: json["account_holder_name"],
            bankName: json["bank_name"],
            branchName: json["branch_name"],
            accountNumber: json["account_number"],
            swiftCode: json["swift_code"],
        );
    
        Map<String, dynamic> toMap() => {
            "account_holder_name": accountHolderName,
            "bank_name": bankName,
            "branch_name": branchName,
            "account_number": accountNumber,
            "swift_code": swiftCode,
        };
    }
    

    It might not have the exact format like you wish, but you can tweak it to your wishes and get a good idea of how to possibly do it

    Login or Signup to reply.
  4. You can see this example:

    class User {
    int id;
    String name;
    
    User({
        required this.id,
        required this.name,
    });
    
    factory User.fromJson(Map<String, dynamic> json) => User(
        id: json["id"],
        name: json["name"],
    );
    
    Map<String, dynamic> toJson() => {
        "id": id,
        "name": name,
    };
    }
    
    
    String? User;
    var getUserURL = Uri.parse("https://");
    
    Future<void> getUser(String phoneNumber, String password) async {
      String clientHashString = userModel.clientHash!;
      final jsonBody = {'phoneNumber': phoneNumber, 'password': password};
    
    try {
      final response = await http.post(getUserURL, body: jsonBody);
      if (response.statusCode == 200) {
        final userObject = json.decode(response.body);
        User = User.fromJson(userObject);
        print("User Loaded");
      } else {
        customSnackBar("error_text".tr, "something_went_wrong_text".tr, red);
        print(response.body);
      }
    } catch (e) {
      throw Exception('Failed to load User');
    }
    

    }

    if you have serval JSON Object then try this, you can try this in your model, but you have to create another model of you serval json objects:

    coupon: json["coupon"] != null ? CouponTransactionModel.fromJson(json["coupon"]) : null,
    

    In your case:

    class DriversLicense {
    int id;
    String name;
    
    DriversLicense({
        required this.id,
        required this.name,
    });
    
    factory DriversLicense.fromJson(Map<String, dynamic> json) => DriversLicense(
        id: json["id"],
        name: json["name"],
    );
    
    Map<String, dynamic> toJson() => {
        "id": id,
        "name": name,
    };
    }
    

    User Model this function will be modified like this:

    factory User.fromJson(Map<String, dynamic> json) => User(
        id: json["id"],
        name: json["name"],
        drivingLicense: DrivingLicense.fromJson(json["**drivers_license**"])
    );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search