k-paxian / dart-json-mapper

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

Default discriminatorValue may not work. #217

Closed rxvincent closed 1 year ago

rxvincent commented 1 year ago

Line 224-228 in mapper.dart from version 2.2.9. It seems that code would never run when discriminatorValue is null, which make the default value of discriminatorValue is always null.

k-paxian commented 1 year ago

Can you illustrate your case with the failing unit test please? That way it would be more productive and fast to correct

rxvincent commented 1 year ago

I have a base class with below statement

@jsonSerializable
@Json(discriminatorProperty: 'type')
abstract class BaseAction {
  String? type;
}

and then I have a class implement

@jsonSerializable
class ShowRectangleAction extends BaseAction {
  // properties
}

Serialize has no error but when I try to deserialize previous serialized json string. It lead to a JsonMapperSubtypeError error.

In my case, all validDiscriminators is null.

rxvincent commented 1 year ago

In mapper.dart when deserialize, method _detectObjectType need to find a Type from _discriminatorToType map. Here, the discriminatorValue can get a correct class name. But the question is in_discriminatorToType. I can only find there is one method to update this map is _updateInternalMaps(). And only those class with jsonMeta.discriminatorValue != null would trigger _discriminatorToType.putIfAbsent to update this map.

k-paxian commented 1 year ago

Please take a look at this issue. Probably it would be useful to rely on that as well. What do you think?

@jsonSerializable
@Json(discriminatorProperty: 'type')
abstract class BaseAction {
  @JsonProperty(ignore: true)
  Type get type => runtimeType;
}

Anyway, I'd love to see a test somewhere here which is illustrating your case