如何实现将复杂类型序列化/反序列化为简单类型的Newtonsoft JSON转换器

时间:2017-08-13 15:50:21

标签: c# json serialization json.net json-deserialization

我希望实施https://github.com/HeadspringLabs/Enumeration。目前,当我尝试序列化/反序列化Enumeration时,它将它序列化为一个复杂的对象。例如,对象颜色:

public class Color : Enumeration<Color, int>
{
    public static readonly Color Red = new Color(1, "Red");
    public static readonly Color Blue = new Color(2, "Blue");
    public static readonly Color Green = new Color(3, "Green");

    private Color(int value, string displayName) : base(value, displayName) { }
}

将序列化为

{ 
    "_value": 2, 
    "_displayName": "Something" 
}

在像这样的复杂对象中:

public class OtherClass
{
    public Color Color {get; set;}
    public string Description {get; set;}
}

它会像这样序列化:

{
    "Description" : "Other Description",
    "Color" :
    { 
        "_value": 2, 
        "_displayName": "Something" 
    }
}

有没有办法让json转换序列化这样的复杂对象:

{
    "Description" : "Other Description",
    "Color" : 2
}

我可以使用Enumeration类中的FromValue方法从值中创建正确的Color对象。我似乎无法使json转换将属性值作为Color对象的“值”。

我可以用什么方式编写转换器的WriteJson和Create方法来实现?

public class EnumerationConverter : JsonCreationConverter<IEnumeration>
        {
            public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
            {
            }

            protected override IEnumeration Create(Type objectType, JObject jObject)
            {
            }
        }

1 个答案:

答案 0 :(得分:2)

您可以为Headspring.Enumeration<T, int> - 派生类创建一个通用转换器,如下所示:

class EnumerationConverter<T> : JsonConverter where T : Headspring.Enumeration<T, int>
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(T);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        int val = Convert.ToInt32(reader.Value);
        return Headspring.Enumeration<T, int>.FromValue(val);
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var enumVal = (Headspring.Enumeration<T, int>)value;
        writer.WriteValue(enumVal.Value);
    }
}

要使用转换器,请在您的枚举类中添加[JsonConverter]属性,如下所示:

[JsonConverter(typeof(EnumerationConverter<Color>))]
public class Color : Headspring.Enumeration<Color, int>
{
    public static readonly Color Red = new Color(1, "Red");
    public static readonly Color Blue = new Color(2, "Blue");
    public static readonly Color Green = new Color(3, "Green");

    private Color(int value, string displayName) : base(value, displayName) { }
}

这是一个往返演示:https://dotnetfiddle.net/CZsQab