How can I use generic structure with JsonSerializable

78 Views Asked by At

Since my data can be of Cart or List type, I wanted to use a generic structure.What could I have done wrong in my code when using generic type with JsonSerializable?.My codes are as in the photo. How can I use the generic structure with JsonSerializable? This is the error I get;

When you run it in debug mode, in the static T _fromJson<T>(Object json) method return _fromJson(json); It stops and gives this error =>Parse Error: Stack Overflow - response body: {data: [{id: 1, firmno: 2, delete: 0, code: CR00001,}]}

enter image description here My Codes;

 @JsonSerializable(explicitToJson: true,genericArgumentFactories: true)
class CartResponseModel<T> extends INetworkModel<CartResponseModel>  {
  @JsonKey(fromJson: _fromJson, toJson: _toJson)
  final T? data;
  final bool? success;
  final String? message;
  static T _fromJson<T>(Map<String, dynamic> map) {
    // same logic as JsonConverter example
  
    return _fromJson(map);
  }
 
  static Object _toJson<T>(T object) {
    // same logic as JsonConverter example
    return _toJson(object);
  }
  CartResponseModel({this.data, this.success, this.message});
  @override
  CartResponseModel fromJson(Map<String, dynamic> json) {
   return _$CartResponseModelFromJson<T>(json, (json) => _fromJson(json!));
  }
  @override
  Map<String, dynamic>? toJson() {
    return _$CartResponseModelToJson(this, (value) => _toJson(value));
  }
  factory CartResponseModel.fromJson(Map<String ,dynamic>json){
    return _$CartResponseModelFromJson<T>(json, (json) => _fromJson(json!));
  }
}
1

There are 1 best solutions below

1
Yoosin Paddy On

If I understood you well, you may need to check if abject is a list before serialization.

static T _fromJson<T>(Map<String, dynamic> map) {
  if (T == List) {
    if (map.containsKey('data') && map['data'] is List) {
      List<dynamic> jsonDataList = map['data'];
      List<T> resultList = [];
      for (var jsonData in jsonDataList) {
        resultList.add(_fromJson<YourCustomClass>(jsonData));
      }
      return resultList as T;
    } else {
      return [] as T;
    }
  } else {
    return YourCustomClass.fromJson(map) as T;
  }
}

Let me know if this is what you are looking for. Provide more clarification if not