Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

json_serializable enum values in dart

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"?

like image 211
cjmarques Avatar asked Apr 02 '19 02:04

cjmarques


People also ask

Does Dart have enums?

Enumerated types (also known as enumerations or enums) are primarily used to define named constant values. The enum keyword is used to define an enumeration type in Dart.

What is enum in Dart flutter?

An enumeration in Dart is a set of symbolic names (members) bound to unique, constant values. Within an enumeration, the members can be compared by identity, and the enumeration itself can be iterated over. An enumeration can be declared by using the enum keyword: enum Aniaml {dog, cat, chicken, dragon}

What is serializable in flutter?

Flutter is a portable UI toolkit. In other words, it's a comprehensive app Software Development toolkit (SDK) that comes complete with widgets and tools. Flutter is a free and open-source tool to develop mobile, desktop, web applications.

Why enum is used in flutter?

Enums are an essential part of programming languages. They help developers define a small set of predefined set of values that will be used across the logics they develop. In Dart language, which is used for developing for Flutter, Enums have limited functionality.


1 Answers

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;
}
like image 154
caneva20 Avatar answered Nov 15 '22 10:11

caneva20