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

I'd like to use Dart's new (experimental) function enum

instead of using stacks of static constant strings, but what's the best way to serialize / deserialize variables enum

using JSON? I made it work, but there is definitely 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 are serializing using the index, you might block to keep the enums in the same order forever, so I would rather use some kind of string form. Has anyone figured this out?

+3


source to share


1 answer


As one of the previously suggested answers, if you are using the same implementation on the client and server, then serializing the name I think is the best way and respects the open / closed principle in SOLID design by pointing out that:

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

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

At the bottom, serialize the name of your enum, and to deserialize it correctly, write a small function that specifies an Enum as a String, iterates over all the members of the Enum, and returns the appropriate one. For example:

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

      



So, for serialization:

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

      

And for deserialization:

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

      

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

+1


source







All Articles