自定义反序列化dart对象



我有哪些类:

class Student {
String name;
String family;
}
class Info {
int age;
String phone;
}

但服务器会给我一个类似json的:

{
"name": "mohammad",
"family": "nasr",
"age": 23,
"phone": "+9345687544",
}

我想要的是像这样的课程

@JsonSerializable()
class JsonResponse {
Student student;
Info info;
}

但问题是,我会给出jsonDecoding错误,因为我的JsonResponse类与服务器响应不匹配。

但我希望我的JsonResponse在那个表格上,

如果您希望JsonResponse类采用形式

@JsonSerializable(explicitToJson: true)
class JsonResponse {
Student student;
Info info;
}

并且序列化该类,您的响应将以{ student: {name: mohammad, family: nasr}, info: {age: 23, phone: +9345687544} },的形式出现,因此您应该更改JsonResponse类或使用此

JsonResponse jsonResponse = JsonResponse.fromJson(
Student.fromJson(jsonData), Info.fromJson(jsonData),
);

只需创建一个反序列化方法fromJson,如下所示:

class Info {
int age;
String phone;
Info({this.age, this.phone});
factory Info.fromJson(Map<String, dynamic> json) {
if(json == null) return null;

return Info(
age: json['age'],
phone: json['phone'],
);
}
}
class Student {
String name;
String family;
Student({this.name, this.family});
factory Student.fromJson(Map<String, dynamic> json) {
if(json == null) return null;

return Student(
name: json['name'],
family: json['family'],
);
}
}
class JsonResponse {
Student student;
Info info;
JsonResponse({this.student, this.info});
factory JsonResponse.fromJson(Map<String, dynamic> json) {
if(json == null) return null;

Student student = Student.fromJson(json);
Info info = Info.fromJson(json);
return JsonResponse(student: student, info: info);
}
}

CCD_ 5将接收来自服务器的CCD_;将其转换为相应的模型对象。

最新更新