当我尝试使用 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
注意:主键是一个List<int>
看起来错误是因为它的父类"实体",该类是这样的:
[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转换为"实体"类型(其父类)。
我无法删除实体(父类),因为它已在很多地方使用。
请指教。
谢谢
终于找到了解决方案。该问题是由于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;
}
}
http://json.codeplex.com/workitem/16554
这不是一个真正的答案 - 这是一个"这工作正常":
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]}