我的应用目前使用自定义类作为每个API响应的模型。
但我正在尝试更改它,以优化一些小细节,所以我正在尝试实现一个名为ApiResponse的类包装器。
但静态调用和方法不起作用,无法进行fromJson和toJson转换。
我会举个例子来说明我正在尝试的内容。
MyModel -> 响应的类。 ApiResponse -> 包含任何模型类的主类,并必须作为其本身调用子方法'fromjson/tojson'。 Test -> 用于测试目的的类,错误注释在类中。
class MyModel {
String id;
String title;
MyModel({this.id, this.title});
factory MyModel.fromJson(Map<String, dynamic> json) {
return MyModel(
id: json["id"],
title: json["title"],
);
}
Map<String, dynamic> toJson() => {
"id": this.id,
"title": this.title,
};
}
class ApiResponse<T> {
bool status;
String message;
T data;
ApiResponse({this.status, this.message, this.data});
factory ApiResponse.fromJson(Map<String, dynamic> json) {
return ApiResponse<T>(
status: json["status"],
message: json["message"],
data: (T).fromJson(json["data"])); // The method 'fromJson' isn't defined for the type 'Type'.
// Try correcting the name to the name of an existing method, or defining a method named 'fromJson'.
}
Map<String, dynamic> toJson() => {
"status": this.status,
"message": this.message,
"data": this.data.toJson(), // The method 'toJson' isn't defined for the type 'Object'.
// Try correcting the name to the name of an existing method, or defining a method named 'toJson'
};
}
class Test {
test() {
ApiResponse apiResponse = ApiResponse<MyModel>();
var json = apiResponse.toJson();
var response = ApiResponse<MyModel>.fromJson(json);
}
}
response.data.id
吗?这应该没有问题。 - Miguel RuivoList<MyModel>
呢? - FradeMyModel
的集合,而MyModel
本身是可序列化的。 - Miguel Ruivo