当我尝试使用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转换为“entity”类型(其父类)..
我无法删除实体(父类),因为它已在很多地方使用过。
请建议。
由于
答案 0 :(得分:2)
终于找到了解决方案。
问题是因为override bool Equals(object obj)
方法中的代码很差。
正确的代码是:
public override bool Equals(object obj)
{
if (obj is Entity)
{
Entity other = (Entity) obj;
return this.Id == other.Id;
}
else
{
return false;
}
}
答案 1 :(得分:0)
这不是一个真正的答案 - 这是“这很好”:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
public class Entity { }
public class CalculationBasis { }
public class PeriodSelectionType { }
[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; }
}
class program
{
static void Main()
{
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.NullValueHandling = NullValueHandling.Ignore;
settings.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat;
var ObjectOfBusiness = new Business
{
TemplateName = "abc",
CalculationBasis = new CalculationBasis(),
PeriodSelectionType = new PeriodSelectionType(),
PeriodEndDate = new DateTime(),
mainKeys = new int[] { 1, 2, 3, 4, 5 }
};
var strJson = JsonConvert.SerializeObject(ObjectOfBusiness, settings);
//...
var obj = JsonConvert.DeserializeObject<Business>(strJson, settings);
// ^^^^ all good
}
}
所以:如果你能展示一个失败的案例,或者给我们提供更多线索,那将是非常好的。有关信息,上面的JSON是:
{"TemplateName":"abc","CalculationBasis":{},"PeriodSelectionType":{},"PeriodEndDate":"\/Date(-62135596800000)\/","mainKeys":[1,2,3,4,5]}