So I have this api call that have a response in the form of: boolean:successful, int:responseCode, String:reponse and T:Data. The Data is a generic, I could be string, int, DataModel etc. My issue is I can not conver the Json or String from of Data to an object as the type is generic. I try to have the deseralization for a data model called event resource. and it works if I do EventResource.fromJson(json['Data'])
but I can not set that to Data
. I have looked on stack overflow and found this one post similar to mine here. But when I try to implement the answer it fails stating that it can not find the constructor _fromJson
even though I had one.
This is how I call fromJson
:
ResponseModel responseModel = ResponseModel.fromJson(json.decode(response.body));
My Class (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,
};
}
}