schultek / dart_mappable

Improved json serialization and data classes with full support for generics, inheritance, customization and more.
https://pub.dev/packages/dart_mappable
MIT License
161 stars 23 forks source link

MapperException: Failed to decode (MyClassA<MyFirstDto>).request(List<MyClassB<UnresolvedType>>): Unknown type List<MyClassB<UnresolvedType>>. Did you forgot to annotate the class or register a custom mapper? #210

Closed DevThibautMonin closed 3 months ago

DevThibautMonin commented 3 months ago

Hello,

I'm encountering a problem when using the dart_mappable package to deserialize JSON into my objects.

The API im using returns different types of lists with the same structure (a message and a list of another object containing a list). I'm trying to pass the data type of the JSON objects as a generic type parameter. However, it seems like this type cannot be resolved.

Is this behavior normal and due to me using dart_mappable incorrectly, or is this unexpected?

Thank you in advance for your help.

Here are the classes I'm using. Depending on the API endpoint I need, I'll switch between different DTOs to retrieve the correct data.

@MappableClass()
class MyClassA<T> with MyClassAMappable<T> {
  final String message;
  final List<MyClassB<T>> request;

  const MyClassA({
    required this.message,
    required this.request,
  });
}

@MappableClass()
class MyClassB<T> with MyClassBMappable<T> {
  final int pageIndex;
  final List<T> data;

  const MyClassB({
    required this.pageIndex,
    required this.data,
  });
}

@MappableClass()
class MyFirstDto {
  final String firstProperty;
  final String secondProperty;

  const MyFirstDto({
    required this.firstProperty,
    required this.secondProperty,
  });
}

@MappableClass()
class MySecondDto {
  final String thirdProperty;
  final String fourthProperty;

  const MySecondDto({
    required this.thirdProperty,
    required this.fourthProperty,
  });
}

var resultModel = MyClassAMapper.fromJson<MyFirstDto>(json);
var resultModel = MyClassAMapper.fromJson<MySecondDto>(json);

No matter which DTO I use as the generic type, I always get this error, as if dart_mappable is unable to resolve the generic type.

MapperException: Failed to decode (MyClassA).request(List<MyClassB>): Unknown type List<MyClassB>. Did you forgot to annotate the class or register a custom mapper?

Thank's for help !

schultek commented 3 months ago

You need to call

MyFirstDtoMapper.ensureInitialized();
MySecondDto.ensureInitialized();

before doing any decoding.

DevThibautMonin commented 3 months ago

Ok, I tried and it seems to work, but I didn't see anything written in the documentation about this, I think.

Do I also need to call the ensureInitialize() method for all the other classes in general or only when I encounter this error?

EDIT : Ok, I finally found the part where it was written, my bad.

Thanks for help !

schultek commented 3 months ago

Only when using generic type params (<SomeClass>)