Shino Lex
Shino Lex

Reputation: 525

Serializing and deserializing enum with flag attribute using json

I try to serialize my model object using JSON. I have no problem with doing this and I know how to deserialize it but in this case I don't get the result as I expected. I'll give my model class and also an example.

This is my class

public class ShortcutsModel
    {
        public string shortcutName { get; set; } = string.Empty;
        public ModifierKeys modifierKeys { get; set; }
        public Keys keys { get; set; }
    }

both ModifierKeys and Keys are enums and they both have flags attribute. ModifierKeys is custom and keys is the one inside Forms namespace. Anyway, I fill my object like this :

 ShortcutsModel scm = new ShortcutsModel();
 scm.shortcutName = "Load";
 cm.modifierKeys = Models.Enums.ModifierKeys.Control | Models.Enums.ModifierKeys.Alt;
 scm.keys = Keys.H | Keys.G;

without any problem, after that I serialize it like this in my properties's set :

string JsonString = JsonConvert.SerializeObject(value);

I get the JSON string. It looks like this :

{"shortcutName":"Load","modifierKeys":3,"keys":79}

so far there is no problem. I save this value and want to get it back as I saved but when I deserialize it like this :

ShortcutsModel ReturningValue = JsonConvert.DeserializeObject<ShortcutsModel>(JSONString);

I don't get the same object as I serialized. After deserializing my class instance's keys property shows me Keys.O which is wrong because it was H+G when I serialized it.

I'm not sure why this is happening but I assume it's because my custom enum extends uint but the default Keys enum does not. Can someone provide me a way to deserialize my JSONString without this problem?

Thanks..

Upvotes: 2

Views: 2807

Answers (1)

mjwills
mjwills

Reputation: 23898

The issue is that:

Keys.H | Keys.G

is equivalent to:

Keys.O

While Keys is a flags enum (and thus you can use |) you can only really use it with the modifier keys, such as:

Shift 65536 The SHIFT modifier key.

So:

Keys.H | Keys.Shift

would be fine, but not:

Keys.H | Keys.G

For your specific context, I'd recommend serialising an array of Keys.

Upvotes: 3

Related Questions