我想知道如何将嵌套 json 解析为具有泛型类型的类。我的目的是用代码和消息包装来自后端的响应(例如包含令牌的loginRespose)
I have
class BaseResponse<T>{
int code;
String message;
T responseObject;
BaseResponse.fromJson(Map<String, dynamic> parsedJson)
: code = parsedJson['Code'],
message = parsedJson['Message'],
responseObject = T.fromJson(parsedJson['ResponseObject']); //This is what I'd like to do
}
显然最后一行会抛出错误,因为 T 没有命名构造函数“fromJson”。
我尝试向类型添加一些限制,但没有找到任何解决方案。您知道如何实现这一目标吗?
你不能做这样的事情,至少在颤振中不能。作为dart:mirror
已禁用,并且没有类构造函数的接口。
你必须采取不同的路线。
我建议使用 POO 代替。你会在这里放弃反序列化responseObject
从你的BaseResponse
。然后有子类BaseResponse
处理这个反序列化
通常,每种类型都有一个子类:
class IntResponse extends BaseResponse<int> {
IntResponse.fromJson(Map<String, dynamic> json) : super._fromJson(json) {
this.responseObject = int.parse(json["Hello"]);
}
}
然后,您可以通过添加自定义工厂构造函数来隐藏这个混乱BaseResponse
使其使用起来更加方便。
class BaseResponse<T> {
int code;
String message;
T responseObject;
BaseResponse._fromJson(Map<String, dynamic> parsedJson)
: code = parsedJson['Code'],
message = parsedJson['Message'];
factory BaseResponse.fromJson(Map<String, dynamic> json) {
if (T == int) {
return IntResponse.fromJson(json) as BaseResponse<T>;
}
throw UnimplementedError();
}
}
然后直接实例化所需的类型,或使用工厂构造函数:
final BaseResponse foo = BaseResponse.fromJson<int>({"Hello": "42", "Code": 42, "Message": "World"});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)