问题描述
因此,我有这个api调用,其响应形式为:布尔值:成功,整数:responseCode,字符串:response和T:Data。数据是通用的,我可以是字符串,整数,数据模型等。我的问题是,由于类型是通用的,我无法将数据的Json或字符串转换为对象。我尝试对称为事件资源的数据模型进行反序列化。如果我执行EventResource.fromJson(json['Data'])
,它就可以工作,但是我不能将其设置为Data
。我查看了堆栈溢出,发现这篇文章与我的here类似。但是,当我尝试实现答案时,它无法说明即使我有一个构造函数,_fromJson
也找不到。
这就是我所说的fromJson
:
ResponseModel responseModel = ResponseModel.fromJson(json.decode(response.body));
我的班级(ResponseModel):
import 'EventResource.dart';
import 'dart:convert' show json;
class ResponseModel<T> {
var successful;
int responseCode;
String response;
T Data;
ResponseModel.fromJson(Map<String,dynamic> json){
successful = json['successful'];
responseCode = json['responseCode'];
response = json['response'];
Data = Data is EventResource? EventResource.fromJson(json['Data']) :json['Data']; // this is what I want but cant get to work
}
Map<String,dynamic> toJson() {
return {
'successful': successful,'responseCode': responseCode,'response': response,'Data': Data,};
}
}
解决方法
因此,在花了一些时间后,我意识到而不是将Data
用作泛型,而是可以将其分配为类型var
,并且它将接收任何数据,并且我们可以轻松地将其抛弃强制转换仿制药等问题。
class ResponseModel {
var successful;
int responseCode;
String response;
var Data;
ResponseModel.fromJson(Map<String,dynamic> json){
successful = json['successful'];
responseCode = json['responseCode'];
response = json['response'];
Data = Data is EventResource? EventResource.fromJson(json['Data']) :json['Data'];
}
Map<String,dynamic> toJson() {
return {
'successful': successful,'responseCode': responseCode,'response': response,'Data': Data,};
}
}