JsonSerializer无法反序列化枚举值

时间:2016-02-18 07:44:49

标签: c# json

我有一个ModelChangeInfo对象,用于定义两个枚举:ModelTypeChangeType。当我反序列化ModelChangeInfo个对象时,只有ChangeType值可以反序列化,ModelType不能,ModelType值为null。 这是我的代码

 public class ModelChangeInfo
{
    public ModelChangeInfo(Guid id, ModelType? modelType, ChangeType? changeType, ParentInfo parentInfo = null)
    {
        Id = id;
        ElementType = modelType;
        ChangeType = changeType;
        ParentInfo = parentInfo;
    }

    /// <summary>
    /// Gets model's id
    /// </summary>
    public Guid Id { get; private set; }
    /// <summary>
    /// Gets model's element type
    /// </summary>
    public ModelType? ElementType { get; private set; }
    /// <summary>
    /// Gets change type
    /// </summary>
    public ChangeType? ChangeType { get; private set; }
    /// <summary>
    /// Gets parent information
    /// </summary>
    public ParentInfo ParentInfo { get; private set; }

    public override string ToString()
    {
        return string.Format("ElementType {0}. ChangeType {1}. Parent ElementType {2}", ElementType, ChangeType, ParentInfo.ElementType);
    }
}

   public class ParentInfo
{
    public ParentInfo(Guid id, ModelType? modelType)
    {
        Id = id;
        ElementType = modelType;
    }

    /// <summary>
    /// Gets model's id
    /// </summary>
    public Guid Id { get; private set; }
    /// <summary>
    /// Gets model's element type
    /// </summary>
    public ModelType? ElementType { get; private set; }
}

[JsonConverter(typeof(StringEnumConverter))]
public enum ModelType
{
    Network,
    TradingPartner,
    Transaction,
    Task,
    File
}

[JsonConverter(typeof(StringEnumConverter))]
public enum ChangeType
{
    Add,
    Update,
    Delete
}

public class JsonDemo
{
    static void Main(string[] args)
    {
        ParentInfo parentInfo = new ParentInfo(Guid.NewGuid(), ModelType.TradingPartner);
        ModelChangeInfo modelChangeInfo = new ModelChangeInfo(Guid.NewGuid(), ModelType.File, ChangeType.Update, parentInfo);

        JsonSerializer serializer = new JsonSerializer();

        using (StreamWriter sw = new StreamWriter(@"C:\json.txt"))
        {
            using (JsonWriter writer = new JsonTextWriter(sw))
            {
                serializer.Serialize(writer, modelChangeInfo);
            }
        }

        using (StreamReader sr = new StreamReader(@"D:\json.txt"))
        {
            using (JsonReader reader = new JsonTextReader(sr))
            {
                ModelChangeInfo temp = serializer.Deserialize<ModelChangeInfo>(reader);
                Console.WriteLine(temp);
            }
        }

        Console.Read();
    }
}

0 个答案:

没有答案