【问题标题】:Serializing and deserializing enum with flag attribute using json使用json对带有标志属性的枚举进行序列化和反序列化
【发布时间】:2019-07-26 12:18:33
【问题描述】:

我尝试使用 JSON 序列化我的模型对象。我这样做没有问题,我知道如何反序列化它,但在这种情况下,我没有得到预期的结果。我会给出我的模型类和一个例子。

这是我的课

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

ModifierKeys 和 Keys 都是枚举,它们都有 flags 属性。 ModifierKeys 是自定义的,键是 Forms 命名空间中的一个。无论如何,我这样填充我的对象:

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

没有任何问题,之后我在我的属性集中像这样序列化它:

string JsonString = JsonConvert.SerializeObject(value);

我得到 JSON 字符串。它看起来像这样:

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

到目前为止没有问题。我保存了这个值并希望在保存时将其取回,但是当我像这样反序列化它时:

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

我没有得到与序列化相同的对象。反序列化我的类实例的 keys 属性后显示 Keys.O 这是错误的,因为我序列化它时它是 H+G。

我不确定为什么会发生这种情况,但我认为这是因为我的自定义枚举扩展了 uint,但默认的 Keys 枚举没有。有人可以提供一种方法来反序列化我的 JSONString 而不会出现这个问题吗?

谢谢..

【问题讨论】:

  • scm.keys = Keys.H | Keys.G; 请在该行之后设置一个断点。运行到断点。转到Immediate Window。输入?scm.keys。结果是什么?这告诉你什么?
  • 永远不要使用|,除非所有标志都是 2 的幂,这里发生的情况是 G 的值为 71,而 H 为 72,或者它们给出 79,即 O
  • 当我在即时 Windows 中检查 ?scm.keys 时,我看到了字母“O”,我猜这很奇怪?

标签: c# json.net


【解决方案1】:

问题是:

Keys.H | Keys.G

相当于:

Keys.O

虽然Keys 是一个标志枚举(因此您可以使用|),但您只能真正将它与modifier 键一起使用,例如:

Shift 65536 SHIFT 修饰键。

所以:

Keys.H | Keys.Shift

会很好,但不是:

Keys.H | Keys.G

对于您的具体情况,我建议序列化一个 Keys 数组。

【讨论】:

  • 谢谢解释,下次我用FlagsAttribute的时候会小心的:)
  • 我一直认为这是对 Flags 属性的错误使用。当我在逻辑上想到一个标志时,我认为它是互斥的(即位图或 2 的幂)。但是,来自Microsoft documentationWarning: Do not use the values in this enumeration for combined bitwise operations. The values in the enumeration are not mutually exclusive.
  • @WonkotheSane 如果你没有预料到,那肯定会令人困惑。
猜你喜欢
  • 2022-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-29
  • 1970-01-01
  • 2017-04-16
  • 2013-05-20
  • 1970-01-01
相关资源
最近更新 更多