dart-lang / sdk

The Dart SDK, including the VM, JS and Wasm compilers, analysis, core libraries, and more.
https://dart.dev
BSD 3-Clause "New" or "Revised" License
10.31k stars 1.59k forks source link

pkg:json - Support for enums #55760

Open pattobrien opened 6 months ago

pattobrien commented 6 months ago

The following code snippet throws an error for enums.

@JsonCodable()
class Foo {
  final MyEnum myEnum;
  //    ^^^^^^ ERROR: Only classes are supported as field types for serializable classes dart(macro_error)
}

enum MyEnum { a }

I realize that EnumDeclarations are generally not yet supported by macros, but since this is basic functionality preventing any future migration, that this would be beneficial to document.

info

- Dart 3.5.0-159.0.dev (dev) (Wed May 15 13:03:12 2024 -0700) on "macos_arm64"
- on macos / Version 14.4.1 (Build 23E224)
- locale is en-US
FarisArmoush commented 6 months ago

@JsonCodable annotation already supports enums, but you have to make one extra step for it to work, which is adding @JsonValue annotation for each value in the enum.

enum Status {
  @JsonValue('active')
  active,
  @JsonValue('inactive')
  inactive,
  @JsonValue('pending')
  pending,
}
1l0 commented 6 months ago

@JsonCodable annotation already supports enums, but you have to make one extra step for it to work, which is adding @JsonValue annotation for each value in the enum.

enum Status {
  @JsonValue('active')
  active,
  @JsonValue('inactive')
  inactive,
  @JsonValue('pending')
  pending,
}

It doesn't work for me. I need this too.

hschaeufler commented 2 months ago

Would also like to use JsonCodable() for enums. It would save a lot of work. In the json_annotation package, for example, there is also a @JsonEnum(). Does anyone know a workaround that I can use for Enums in context with JsonCodable without having to remove JsonCodable?