cjmarques
cjmarques

Reputation: 682

json_serializable enum values in dart

How to use the json_serializable package with enum types. The 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"?

Upvotes: 15

Views: 12691

Answers (1)

caneva20
caneva20

Reputation: 610

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;
}

Upvotes: 27

Related Questions