我有一个ModelChangeInfo对象,用于定义两个枚举:ModelType
和ChangeType
。当我反序列化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();
}
}