【发布时间】:2021-02-12 04:24:40
【问题描述】:
我的应用目前正在为每个 api 响应使用自定义类作为模型。 但我试图改变它,优化一些小东西,所以我试图实现一个类包装器,例如称为 ApiResponse。 但是对于 make fromJson 和 toJson,它的静态调用和方法不能正常工作。
作为示例,我将展示我正在尝试的内容。 MyModel -> 类响应。 ApiResponse -> 内部包含任何模型类的主类,并且必须将子方法称为自身的“fromjson/tojson”。 测试 -> 用于测试目的的类,类上的错误 cmets。
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);
}
}
【问题讨论】:
标签: json api flutter dart response