当我尝试使用 json.net 将对象转换为 json 时出现错误。
错误:
Unable to cast object of type 'System.Collections.Generic.List`1[System.Int32]' to type
'MyNamespace.Domain.Entity'.
要序列化的类:
[Serializable]
public class Business:Entity
{
public virtual string TemplateName { get; set; }
public virtual CalculationBasis CalculationBasis { get; set; }
public virtual PeriodSelectionType PeriodSelectionType { get; set; }
public virtual DateTime PeriodEndDate { get; set; }
public virtual IEnumerable<int> mainKeys { get; set; }
}
序列化代码:
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.NullValueHandling = NullValueHandling.Ignore;
settings.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat;
var strJson = JsonConvert.SerializeObject( ObjectOfBusiness, settings);
反序列化代码:
JsonConvert.DeserializeObject<Business>(ObjectOfBusiness, settings);
当我有值时,我只会收到此错误IEnumerable<int> mainKeys
注意:mainKeys 是一个List<int>
看起来错误是因为它的父类 "Entity" ,类是这样的:
[Serializable]
public abstract class Entity
{
public Entity()
{
}
public Entity(int id)
{
this.Id = id;
}
public virtual int Id { get; set; }
public override bool Equals(object obj)
{
Entity other = (Entity)obj;
return this.Id == other.Id;
}
public override int GetHashCode()
{
return this.Id.GetHashCode();
}
}
不知道为什么 json.net 试图将 IEnumerable 转换为“实体”类型(它的父类)..
我无法删除实体(父类),因为它在很多地方都被使用过..
请建议。
谢谢