What is the best way to serialize/deserialize Dart's new enum with JSON?

dart, enums, json

Solution

As one of the answer previously suggested, if you share the same implementation on the client and server, then serializing the name is I think the best way and respects the open/closed principle in the S.O.L.I.D design, stating that:

"software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification"

Using the index instead of the name would mess up all the logic of your code if you ever need to add another member to the Enum. However using the name would allow extension.

Bottom line, serialize the name of your enum and in order to deserialize it properly, write a little function that given an Enum as a String, iterates over all the members of the Enum and returns the appropriate one. Such as:

Status getStatusFromString(String statusAsString) {
  for (Status element in Status.values) {
     if (element.toString() == statusAsString) {
        return element;
     }
  }
  return null;
}

So, to serialize:

Status status1 = Status.stopped;
String json = JSON.encode(status1.toString());
print(json) // prints {"Status.stopped"}

And to deserialize:

String statusAsString = JSON.decode(json);
Status deserializedStatus = getStatusFromString(statusAsString);
print(deserializedStatus) // prints Status.stopped

This is the best way I've found so far. Hope this helps !

Problem

I'd like to make use of Dart's new (experimental) `enum` feature instead of using stacks of static const Strings, but what's the best way to serialize/deserialize `enum` variables using JSON? I've made it work this way, but surely there's a better solution: ``` enum Status { none, running, stopped, paused } Status status1 = Status.stopped; Status status2 = Status.none; String json = JSON.encode(status1.index); print(json); // prints 2 int index = JSON.decode(json); status2 = Status.values[index]; print(status2); // prints Status.stopped ``` If you serialize using the index, you can get locked into keeping your enums in the same order forever, so I'd much prefer to use some kind of String form. Anyone figured this out?

Original source

Related problems