如何在Flutter中处理包含另一个对象的JSON对象时使用fromJson和toJson函数?

huangapple go评论72阅读模式
英文:

How to use fromJson and toJson when json object have inside another object like this in flutter

问题

class ServiceProviderModel {
  String id = "";
  String sp_id = "";
  String phone_number = "";
  String nic = "";
  String license_id = "";
  String expiry_date = "";
  String user_level = "";
  String gender = "";
  String user_sub_type = "";
  bool is_fleet_owner = false;
  String fleet_id = "";
  Map<String, dynamic> documents = {};
  Map<String, dynamic> payment_parameters = {
    "account_holder_name": "",
    "bank_name": "",
    "branch_name": "",
    "account_number": "",
    "swift_code": ""
  };

  ServiceProviderModel();

  ServiceProviderModel.fromJson(Map json)
      : id = json['id'],
        sp_id = json['sp_id'],
        phone_number = json['phone_number'],
        nic = json['nic'],
        license_id = json['drivers_license']['license_id'],
        expiry_date = json['drivers_license']['expiry_date'],
        user_level = json['user_level'],
        gender = json['gender'],
        user_sub_type = json['user_sub_type'],
        is_fleet_owner = json['is_fleet_owner'],
        fleet_id = json['fleet_id'],
        documents = json['documents'],
        payment_parameters = json['payment_parameters'];

  Map toJson() => {
        'id': id,
        'sp_id': sp_id,
        'phone_number': phone_number,
        'nic': nic,
        'drivers_license': {
          'license_id': license_id,
          'expiry_date': expiry_date,
        },
        'user_level': user_level,
        'gender': gender,
        'user_sub_type': user_sub_type,
        'is_fleet_owner': is_fleet_owner,
        'fleet_id': fleet_id,
        'documents': documents,
        'payment_parameters': payment_parameters,
      };
}
英文:

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

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

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 = &quot;&quot;;
String phone_number = &quot;&quot;;
String nic = &quot;&quot;;
String license_id = &quot;&quot;;
String expiry_date = &quot;&quot;;
String gender = &quot;&quot;;
String user_sub_type = &quot;&quot;;
String document_type_1 = &quot;&quot;;
String document_type_2 = &quot;&quot;;
String first_name = &quot;&quot;;
String last_name = &quot;&quot;;
String email = &quot;&quot;;
String profile_pic_url = &quot;&quot;;
String emergency_contact = &quot;&quot;;
String status = &quot;active&quot;;
ServiceProviderModel();
ServiceProviderModel.fromJson(Map json)
: id = json[&#39;id&#39;],
phone_number = json[&#39;phone_number&#39;],
nic = json[&#39;nic&#39;],
license_id = json[&#39;license_id&#39;],
gender = json[&#39;gender&#39;],
user_sub_type = json[&#39;user_sub_type&#39;],
document_type_1 = json[&#39;document_type_1&#39;],
document_type_2 = json[&#39;document_type_2&#39;],
first_name = json[&#39;first_name&#39;],
last_name = json[&#39;last_name&#39;],
email = json[&#39;email&#39;],
profile_pic_url = json[&#39;profile_pic_url&#39;],
emergency_contact = json[&#39;emergency_contact&#39;],
expiry_date = json[&#39;expiry_date&#39;],
status = json[&#39;status&#39;];
Map toJson() =&gt; {
&#39;id&#39;: id,
&#39;phone_number&#39;: phone_number,
&#39;nic&#39;: nic,
&#39;license_id&#39;: license_id,
&#39;gender&#39;: gender,
&#39;user_sub_type&#39;: user_sub_type,
&#39;document_type_1&#39;: document_type_1,
&#39;document_type_2&#39;: document_type_2,
&#39;first_name&#39;: first_name,
&#39;last_name&#39;: last_name,
&#39;email&#39;: email,
&#39;profile_pic_url&#39;: profile_pic_url,
&#39;emergency_contact&#39;: emergency_contact,
&#39;expiry_date&#39;: expiry_date,
&#39;status&#39;: status,
};
}

答案1

得分: 1

以下是您提供的代码的翻译部分:

通常,您会为子实体创建一个新类,其中包含属性以及它们自己的fromJson和toJson方法。然后在父类的fromJson方法中调用这些方法

示例伪代码:

class DriversLicense {
  final String license_id;
  final String expiry_date;

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

class ServiceProviderModel {
  ...
  DriversLicense drivers_license;
  ...

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

这是我自己项目中的更完整示例。它将类设置为不可变,并提供了一个copyWith方法,用于对新实例应用更改。不包括toJson(),但在结构上基本相同。

import 'package:lon_flutter_poc_app/data/graphql/gen/author.dart';

// 这是由代码生成的。您将失去手动更改!
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});

  // 这是由代码生成的。您将失去手动更改!

  factory Post.fromJson(Map<String, dynamic> json) {
    return Post(
      id: json['id'],
      title: json['title'] ?? "",
      author: Author.fromJson(json['author'] ?? {}),
      votes: json['votes'],
    );
  }

  // 这是由代码生成的。您将失去手动更改!
  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';

// 这是由代码生成的。您将失去手动更改!
class Author {
  final int id;
  final String firstName;
  final String lastName;

  Author({required this.id, required this.firstName, required this.lastName});

  // 这是由代码生成的。您将失去手动更改!

  factory Author.fromJson(Map<String, dynamic> json) {
    return Author(
      id: json['id'],
      firstName: json['firstName'] ?? "",
      lastName: json['lastName'] ?? ""
    );
  }

  // 这是由代码生成的。您将失去手动更改!
  Author copyWith({
    int? id,
    String? firstName,
    String? lastName,
  }) {
    return Author(
      id: id ?? this.id,
      firstName: firstName ?? this.firstName,
      lastName: lastName ?? this.lastName
    );
  }
}

希望这有助于您理解这些代码的翻译。如果您需要进一步的帮助,请随时提问。

英文:

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&lt;String, dynamic&gt; json) {
return DriversLicense(
license_id: json[&#39;id&#39;],
expiry_date: json[&#39;expiry_date&#39;] ?? &quot;&quot;
);
}
}

Psudeo code for you to insert.

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

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 &#39;package:lon_flutter_poc_app/data/graphql/gen/author.dart&#39;;
// 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&lt;String, dynamic&gt; json) {
return Post(
id: json[&#39;id&#39;],
title: json[&#39;title&#39;] ?? &quot;&quot;,
author: Author.fromJson(json[&#39;author&#39;] ?? {}),
votes: json[&#39;votes&#39;],
);
}
// 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 &#39;package:lon_flutter_poc_app/data/graphql/gen/post.dart&#39;;
// 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&lt;String, dynamic&gt; json) {
return Author(
id: json[&#39;id&#39;],
firstName: json[&#39;firstName&#39;] ?? &quot;&quot;,
lastName: json[&#39;lastName&#39;] ?? &quot;&quot;
);
}
// 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
);
}
}

答案2

得分: 1

我建议使用类似 https://app.quicktype.io/ 的工具。输入你的示例JSON可以生成如下内容:

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,
    };
}

它可能不会与你期望的格式完全相同,但你可以根据需要进行调整,以了解如何实现类似的结构。

英文:

I suggest using a tool like https://app.quicktype.io/.
Entering your example JSON can generate this for example

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

答案3

得分: 0

以下是翻译好的内容:

"我找到了一个很好的答案来解决这个问题,我使用以下代码来解决这个问题。这非常简单和清晰。"

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,
      };
}

希望这对你有帮助!

英文:

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 = &quot;&quot;;
String phone_number = &quot;&quot;;
String nic = &quot;&quot;;
Map drivers_license = new Map();
String license_id = &quot;&quot;;
String expiry_date = &quot;&quot;;
String gender = &quot;&quot;;
String user_sub_type = &quot;&quot;;
Map documents = new Map();
String document_type_1 = &quot;&quot;;
String document_type_2 = &quot;&quot;;
String first_name = &quot;&quot;;
String last_name = &quot;&quot;;
String email = &quot;&quot;;
String profile_pic_url = &quot;&quot;;
String emergency_contact = &quot;&quot;;
String status = &quot;active&quot;;
ServiceProviderModel();
ServiceProviderModel.fromJson(Map json)
: id = json[&#39;id&#39;],
phone_number = json[&#39;phone_number&#39;],
nic = json[&#39;nic&#39;],
drivers_license = json[&#39;drivers_license&#39;],
gender = json[&#39;gender&#39;],
user_sub_type = json[&#39;user_sub_type&#39;],
documents = json[&#39;documents&#39;],
first_name = json[&#39;first_name&#39;],
last_name = json[&#39;last_name&#39;],
email = json[&#39;email&#39;],
profile_pic_url = json[&#39;profile_pic_url&#39;],
emergency_contact = json[&#39;emergency_contact&#39;],
status = json[&#39;status&#39;];
Map toJson() =&gt;
{
&#39;id&#39;: id,
&#39;phone_number&#39;: phone_number,
&#39;nic&#39;: nic,
&#39;drivers_license&#39;: drivers_license,
&#39;gender&#39;: gender,
&#39;user_sub_type&#39;: user_sub_type,
&#39;documents&#39;: documents,
&#39;first_name&#39;: first_name,
&#39;last_name&#39;: last_name,
&#39;email&#39;: email,
&#39;profile_pic_url&#39;: profile_pic_url,
&#39;emergency_contact&#39;: emergency_contact,
&#39;status&#39;: status,
};
}

答案4

得分: 0

这是您要翻译的代码部分:

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**"])
);

希望这对您有所帮助。如果您需要进一步的翻译或有其他问题,请告诉我。

英文:

You can see this example:

class User {
int id;
String name;
User({
required this.id,
required this.name,
});
factory User.fromJson(Map&lt;String, dynamic&gt; json) =&gt; User(
id: json[&quot;id&quot;],
name: json[&quot;name&quot;],
);
Map&lt;String, dynamic&gt; toJson() =&gt; {
&quot;id&quot;: id,
&quot;name&quot;: name,
};
}
String? User;
var getUserURL = Uri.parse(&quot;https://&quot;);
Future&lt;void&gt; getUser(String phoneNumber, String password) async {
String clientHashString = userModel.clientHash!;
final jsonBody = {&#39;phoneNumber&#39;: phoneNumber, &#39;password&#39;: 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(&quot;User Loaded&quot;);
} else {
customSnackBar(&quot;error_text&quot;.tr, &quot;something_went_wrong_text&quot;.tr, red);
print(response.body);
}
} catch (e) {
throw Exception(&#39;Failed to load User&#39;);
}

}

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[&quot;coupon&quot;] != null ? CouponTransactionModel.fromJson(json[&quot;coupon&quot;]) : null,

In your case:

class DriversLicense {
int id;
String name;
DriversLicense({
required this.id,
required this.name,
});
factory DriversLicense.fromJson(Map&lt;String, dynamic&gt; json) =&gt; DriversLicense(
id: json[&quot;id&quot;],
name: json[&quot;name&quot;],
);
Map&lt;String, dynamic&gt; toJson() =&gt; {
&quot;id&quot;: id,
&quot;name&quot;: name,
};
}

User Model this function will be modified like this:

factory User.fromJson(Map&lt;String, dynamic&gt; json) =&gt; User(
id: json[&quot;id&quot;],
name: json[&quot;name&quot;],
drivingLicense: DrivingLicense.fromJson(json[&quot;**drivers_license**&quot;])
);

huangapple
  • 本文由 发表于 2023年6月27日 18:54:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/76564138.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定