k-paxian / dart-json-mapper

Serialize / Deserialize Dart Objects to / from JSON
https://pub.dev/packages/dart_json_mapper
Other
400 stars 33 forks source link

Can't convert List<Car> #17

Closed VNAPNIC closed 4 years ago

VNAPNIC commented 4 years ago

// Deserialize print(JsonMapper.deserialize<Person>(personJson));

print to:

Unhandled exception:
type List<dynamic> is not a subtype of type List<Car> of 'value'
#0      _data.<anonymous closure> (file:///E:/Flutter/dart-json-mapper-master/example/example.reflectable.dart:519:61)
#1      _InstanceMirrorImpl.invokeSetter (package:reflectable/src/reflectable_builder_based.dart:346:20)
#2      JsonMapper.deserializeObject.<anonymous closure> (package:dart_json_mapper/json_mapper.dart:523:12)
#3      JsonMapper.enumeratePublicFields (package:dart_json_mapper/json_mapper.dart:296:14)
#4      JsonMapper.deserializeObject (package:dart_json_mapper/json_mapper.dart:502:5)
#5      JsonMapper.deserialize (package:dart_json_mapper/json_mapper.dart:59:21)
#6      main (file:///E:/Flutter/dart-json-mapper-master/example/example.dart:101:20)
#7      _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:301:19)
#8      _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:172:12)
k-paxian commented 4 years ago

Sorry pal, have no idea what are you talking about. "Cart"? show me the whole code if you want help.

Aha, Are you talking about Example.dart? Ok, then you've got me :)

VNAPNIC commented 4 years ago

I used your example, but when I run it and it error

https://github.com/k-paxian/dart-json-mapper/blob/master/example/example.dart

k-paxian commented 4 years ago

Just throw in these lines before deserialization:

  // Because Person has a custom list List<Car>, we have to provide value cast decorator for it
  // to be able to Deserialize
  final iterableCarDecorator = (value) => value.cast<Car>();
  JsonMapper.registerValueDecorator<List<Car>>(iterableCarDecorator);

  // Serialize
  print(JsonMapper.serialize(Person()));

  // Deserialize
  print(JsonMapper.deserialize<Person>(personJson));

Thanks for letting me know.

VNAPNIC commented 4 years ago

woo thank u, I think u should update the example

k-paxian commented 4 years ago

Absolutely! I'll do that thanks to your attention, documentation is going better.

VNAPNIC commented 4 years ago

I think if u remove the registerValueDecorator, well it great :)

k-paxian commented 4 years ago

I would love to get rid of it myself, here is the explanation of why it is like that. Dart language is not allowing another workaround for this case.