11

I'm new to dart development...

I can't figure out how to use the Json_serializable package with enum types. my database has the enum values as an integer, but it looks like JSON_Serializable wants the value to be a string representation of the enum name.. IE:

enum Classification { None, Open, Inactive, Closed, Default, Delete, ZeroRecord }

database has Classification as an integer value (4: which is Default)

when loading from JSON I get an exception

EXCEPTION: Invalid argument(s): 4 is not one of the supported values: None, Open, Inactive, Closed, Default, Delete, ZeroRecord

How do I force JSON_Serializable to treat 4 as "Default"?

cjmarques
  • 632
  • 1
  • 7
  • 17

1 Answers1

22

Basically you have two options. (AFAIK)

In your enum file, for each value you may add a @JsonValue(VALUE) annotation, json_serializable will use that value instead of the name, and it can be anything actually.

You could have your enum as follows:

enum Classification {
  @JsonValue(0)
  None,

  @JsonValue(1)
  Open,

  @JsonValue(2)
  Inactive,

  @JsonValue(3)
  Closed,

  @JsonValue(4)
  Default,

  @JsonValue(5)
  Delete,

  @JsonValue(6)
  ZeroRecord,
}

another thing you can do if you really want a default value, is to use the @JsonKey annotation and set the unknownEnumValue property to the desired default value

class MyModel {
  @JsonKey(unknownEnumValue: Classification.Default)
  Classification classification;
}
caneva20
  • 490
  • 6
  • 14