将自定义Enum序列化为其值

时间:2017-04-26 08:25:49

标签: c# serialization json.net

假设我有自定义枚举

public sealed class Shape
{
    // enum values
    public static readonly Shape Circle = new Shape(100, "Circle");
    public static readonly Shape Square = new Shape(200, "Square");
    public static readonly Shape Rectangle = new Shape(300, "Rectangle");

    // enum value properties 
    public readonly short Number;
    public readonly string Name;

    // private constructor
    private Shape(short number, string name)
    {
        Number = number;
        Name = name;
    }
}

我希望以这种方式支持newtonsoft JSON.Net序列化:

  • Shape.Circle已序列化为100
  • 100被反序列化为Shape.Circle
  • 可选地,字符串"Circle"也被反序列化为Shape.Circle

我可以为类中的此Enum对象的de / -serialization设置逻辑,例如从intstring设置隐式运算符转换或使用一些特殊的JSON.Net属性,属性?我希望Enum对象中包含所有逻辑,因此用户只需将类型标记为Shape,就不需要设置自定义convertors等。

0 个答案:

没有答案
相关问题