json_serializable.dart icon indicating copy to clipboard operation
json_serializable.dart copied to clipboard

[Feature Request] Enum value with enhanced Enums

Open a7md0 opened this issue 2 years ago • 3 comments

Feature request related to Enhanced enums while using JsonValue

  1. Currently, we would have to declare the value twice per Enum value (to allow this package to serialize/deserialize the Enum and to have access to .value)
import 'package:json_annotation/json_annotation.dart';

part 'status_code.g.dart';

enum StatusCode {
  @JsonValue(200)
  success(200),

  @JsonValue(500)
  weird(500),

  const StatusCode(this.value);

  final int value;
}

It would be much better if we could have the generated map EnumMap to use the value specified in the constructor

a7md0 avatar May 10 '22 22:05 a7md0

I have no idea how could generation work in the package, but one possibility will be offer some kind of interface EnumValue<T> to be implemented by the Enum, thus making the T value required to be implemented. Then a check for Enums implementing this interface and use the value passed in the constructor to create the EnumMap with the code generation.

a7md0 avatar May 10 '22 22:05 a7md0

Or we could "steal" the JasonValue annotation and put it on the enum definition with the field name – in the case above "value".

The package is not setup to support adding language-specific features until we're ready to bump the min SDK, so it'll likely be a while until we get there.

kevmoo avatar May 11 '22 23:05 kevmoo

https://github.com/google/json_serializable.dart/pull/1180 bumps the min version of the required SDK – we could entertain this now!

kevmoo avatar Jul 29 '22 23:07 kevmoo

Hey, did this get any updates? I am running the latest version and it's still generating by name. Am I missing something?

memoriasIT avatar Sep 14 '22 17:09 memoriasIT

Looking now!

kevmoo avatar Sep 20 '22 02:09 kevmoo

This feature has been added as of

https://pub.dev/packages/json_annotation/versions/4.7.0 and https://pub.dev/packages/json_serializable/versions/6.4.0

kevmoo avatar Sep 21 '22 00:09 kevmoo

@kevmoo Sorry for coming back on this. Just to make things clear, when using the new syntax of enhanced enums should we still use the @JsonValue annotation on top of each enum value or does the library takes care of it?

Looks that json_convert always generates a string representation of the enum name when there is no @JsonValue and not the declared enum values.

YiannisBourkelis avatar Jan 30 '23 08:01 YiannisBourkelis

Just use @JsonEnum on the enum itself. @JsonValue should no longer be needed.

kevmoo avatar Jan 30 '23 17:01 kevmoo

@kevmoo Perfect! Thank you

YiannisBourkelis avatar Jan 30 '23 19:01 YiannisBourkelis