Can't (de)serialize nested generic classes with Dart freezed and json_serializable

1.4k Views Asked by At

I got a class First defined as:

@freezed
class First<T> with _$First<T> {
  @JsonSerializable(explicitToJson: true)
  factory First({
    required String a,
    @BConverter() required T b,
  }) = _First<T>;

  factory First.fromJson(Map<String, dynamic> json) => _$FirstFromJson(json);
}

where BConverter() is a JsonConverter. So far so good, code generation works without issues.

At this point, I need to add class First into other two classes like this:

@freezed
class Second with _$Second {
  @JsonSerializable(explicitToJson: true)
  factory Second({
    required String c,
    @Default(<First<SomeClass>>[]) List<First<SomeClass>> d,
  }) = _Second;

  factory Second.fromJson(Map<String, dynamic> json) => _$SecondFromJson(json);
}
@freezed
class Third with _$Third {
  @JsonSerializable(explicitToJson: true)
  factory Third({
    required String x,
    @Default(<First<SomeOtherClass>>[]) List<First<SomeOtherClass>> e,
  }) = _Third;

  factory Third.fromJson(Map<String, dynamic> json) => _$ThirdFromJson(json);
}

In the latter two cases, the code generation for the json_serializable part fails with the error:

The argument type 'List<First<dynamic>>' can't be assigned to the parameter type 'List<First<SomeClass>>'.

and

The argument type 'List<Second<dynamic>>' can't be assigned to the parameter type 'List<Second<SomeOtherClass>>'.

The error is generated in the .g.dart file in:

_$_Second _$_$_SecondFromJson(Map<String, dynamic> json) {
  return _$_Second(
    d: (json['d'] as List<dynamic>)
        .map((e) => First.fromJson(e as Map<String, dynamic>))
        .toList(),

  );
}

What am I missing here? What am I doing wrong?

0

There are 0 best solutions below