Skip to content

[Feature Request] Custom fromJson for JsonEnum #1036

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
farukprogrammer opened this issue Nov 21, 2021 · 2 comments
Open

[Feature Request] Custom fromJson for JsonEnum #1036

farukprogrammer opened this issue Nov 21, 2021 · 2 comments

Comments

@farukprogrammer
Copy link

I want to track when unknownValue occurs when parsing fromJson for enum type, so that I can fix the model or tell the BE if something unexpected happen.

In order to do that, I guess we need to be able to inject custom deserialization method, not just mapping. Just like fromJson and toJson in JsonKey.

@jellynoone
Copy link

I have a similar use case, I'd like to handle unknown type or be able to specify an on unknown type value. Something along the lines:

@JsonEnum(onUnknownEnumValue: MyFormType.unknown)
enum MyFormType {
  checkbox, 
  radio,
  unknown,
}

Meaning, if the value in serialized format is 'hidden', its converted to MyFormType.unknown.

I actually see the $enumDecode has an unknownValue paramete that does just that. I just don't know how to cause the generator to use it.

Also:
From previous issues: #778, #653
There seems to be a want to be able to convert enums manually as well ie. have a generated function. Would it be possible to mark a the decoding and encoding functions to be public? Or maybe be able to set them a name?
This way we could optimize away the $enumDecode function and reuse the decoders/encoders throughout the codebase.

Example:

// my_form_type.dart

part 'my_form_type.g.dart';

@JsonEnum(
  alwaysCreate: true,
  onUnknownEnumValue: MyFormType.unknown,
  generateEncoderWithName: 'myFormTypeToValue',
  generateDecoderWithName: 'myFormTypeFromValue',
)
enum MyFormType {
  checkbox,
  radio,
  unknown,
}

// my_form_type.g.dart
MyFormType myFormTypeToValue(String json) {
  switch (json) {
    case 'checkbox':
      return MyFormType.checkbox;
    case 'radio':
      return MyFormType.radio;
  }

  return MyFormType.unknown;
}

String myFormTypeFromValue(MyFormType object) {
  switch (object) {
    case MyFormType.checkbox:
      return 'checkbox';

    case MyFormType.radio:
      return 'radio';

    case MyFormType.unknown:
      return 'unknown';
  }
}

@jellynoone
Copy link

After further digging I saw I missed the JsonKey.unknownEnumValue property. Ignore my previous comment unless the recommended improvements make sense.

I do think unifying enum conversion would be a nice have.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants