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

Cannot deserialize to a class with a constructor that takes an enum #198

Closed Lars-Sommer closed 1 year ago

Lars-Sommer commented 1 year ago

I have this enum:

@JsonSerializable()
enum EActionType { None, Installation, Replacement }

I Have this class:

@JsonSerializable()
class TestModel {
  EActionType type = EActionType.None;
}

I have this json:

var json = {
      'type': 'Installation',
}

Deserializing this works just fine 👌

But I need a constructor in my class to instantiate the model in my code logic:

@JsonSerializable()
class TestModel {
  EActionType type = EActionType.None;

  TestModel(EActionType actionType) {
    type = actionType;
  }
}

Now the deserializing fails with: TypeError (type 'Null' is not a subtype of type 'EActionType')

If I remove the actionType, so the constructor is empty, the deserialization works fine.

Any clues? 🤔

k-paxian commented 1 year ago

well, that should be the easy one, it's not obvious that constructor parameter actionType needs to be mapped to json field type, so you should tell it explicitly how to operate:

@JsonSerializable()
class TestModel {
  EActionType type = EActionType.None;

  TestModel(@JsonProperty(name: 'type') EActionType actionType) {
    type = actionType;
  }
}

This should do the trick, if not let me know.

In your case you have different field names, but there are more cases around that, like:

@jsonSerializable
class Model {
  EActionType _type = EActionType.None;
  EActionType get type {
    return _type;
  }

  Model(EActionType  type) {
    _type = type;
  }
}
Lars-Sommer commented 1 year ago

Makes great sense, and it works ofc :) Thanks alot! 🍺

k-paxian commented 1 year ago

Wow, so generous, thank you so much appreciate that. All I can do for you is my pleasure, challenge me whenever you like

Lars-Sommer commented 1 year ago

This library is priceless, and your ability to help and sort out issues so fast is incredible!