I have list of objects in json form that are coming from an API. These objects have some attributes, the problem is some of the objects have missing attributes. so how to parse the data of the others attributes without error?
for example i have this one missing the attributes of paymentType
"user":{
"id": 6,
"name": "User",
"email": "",
"phone": "123",
"credit": null,
"fireBaseId": null,
"created_at": "2021-10-28T10:28:34.000000Z",
"updated_at": "2021-10-29T22:10:09.000000Z"
},
"paymentType": null,
"booking_type":{
"id": 1,
"name": "Mobile",
"price": 0,
"created_at": null,
"updated_at": null
}
but this all attributs exist:
"user":{
"id": 6,
"name": "User",
"email": "",
"phone": "",
"credit": null,
"fireBaseId": null,
"created_at": "2021-10-28T10:28:34.000000Z",
"updated_at": "2021-10-29T22:10:09.000000Z"
},
"paymentType":{
"id": 1,
"name": "Cash",
"active": 1,
"created_at": "2021-10-29T00:36:06.000000Z",
"updated_at": "2021-10-29T17:24:42.000000Z"
},
"booking_type":{
"id": 2,
"name": "Parking",
"price": 10,
"created_at": null,
"updated_at": null
}
CodePudding user response:
If you feel that some of the attributes might be null, add the null safety to them, then use the if() condition to parse the values from the map to the object's attributes.
This is one possible way. It may not be the ideal one, but it works fine !
class User {
int? id;
String? user;
String? email;
String? phone;
String? credit;
User.fromMap(Map<String, dynamic> map) {
if (map.containsKey('id')) {
this.id = int.parse(map['id']);
}
if (map.containsKey('user')) {
this.user = "${map['user']}";
}
if (map.containsKey('email')) {
this.email = "${map['email']}";
}
if (map.containsKey('phone')) {
this.phone = "${map['phone']}";
}
if (map.containsKey('credit')) {
this.credit = "${map['credit']}";
}
}
}
CodePudding user response:
You can create special object class for paymentType. just try it.
create payment.dart
class PaymentType {
int id;
String name;
int active;
DateTime createdAt;
DateTime updatedAt;
PaymentType({
this.id,
this.name,
this.active,
this.createdAt,
this.updatedAt,
}) ;
factory PaymentType.fromJson(Map<String, dynamic> json) =>PaymentType(
id: json["id"],
name: json["name"],
active: json["active"],
createdAt: DateTime.parse(json["created_at"]),
updatedAt: DateTime.parse(json["updated_at"]),
);
}
And use it like that while parsing:
......
"paymentType" : json["payment_type"] != null ? PaymentType.fromJson(json["payment_type"]) : null;
......
If you have any doubt, just feel free :)
