serialize_enum 0.1.0 serialize_enum: ^0.1.0 copied to clipboard
Json serialization for Dart enumerations without source code generation.
Serialize Dart Enumerations - Example #
Example #
The example below shows the enum AlphabeticOrder
. The generic mixin SerializeByName provides the method toJson
. The enum factory constructor
calls the static method SerializeByName.fromJson
provided by the mixin:
import 'package:serialize_enum/serialize_enum.dart';
enum AlphabeticOrder with SerializeByName<AlphabeticOrder> {
asc,
desc;
/// Reads a json map and returns the corresponding
/// instance of `AlphabeticOrder`.
factory AlphabeticOrder.fromJson(Map<String, dynamic> json) =>
SerializeByName.fromJson(json: json, values: values);
}
Note: The generic type parameter of SerializeByName must be specified. It is used to generate the json map key under which the enum name is stored.
// Code shown above goes here ...
void main() {
const order = AlphabeticOrder.asc;
print('Json map:');
print(order.toJson());
print('\nRevived enum:');
print(AlphabeticOrder.fromJson(order.toJson()));
}
Running the program produces the following console output:
$ dart alphabetic_order_example.dart
Json map:
{alphabeticOrder: asc}
Revived enum:
AlphabeticOrder.asc
Features and bugs #
Please file feature requests and bugs at the issue tracker.