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

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


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 !