英文:
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
[
{
"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,
};
}
答案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<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
);
}
}
答案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 '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
答案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 = "";
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,
};
}
答案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<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**"])
);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论