Bhagyesh
Bhagyesh

Reputation: 700

How to deserialize a string to a object and then set as a generic in flutter

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,
    };
  }
}

Upvotes: 1

Views: 374

Answers (1)

Bhagyesh
Bhagyesh

Reputation: 700

So after sending some time on this I realized rather than have Data be a generic it could be assigned the type var and it would take in any data and we could easily cast it with out having the issues of casting generics etc.

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,
    };
  }

}

Upvotes: 1

Related Questions