自引用循环检测到序列化异常

时间:2013-03-30 18:09:48

标签: json serialization asp.net-web-api

这是我的班级:

public partial class Event
{
    public Event()
    {
        this.Comments = new HashSet<Comment>();
        this.Rates = new HashSet<Rate>();
        this.RawDates = new HashSet<RawDate>();
    }

    public int ID { get; set; }
    public string Title { get; set; }
    public string Summary { get; set; }
    public string SiteURL { get; set; }
    public string ContactEmail { get; set; }
    public string LogoURL { get; set; }
    public int EventType_ID { get; set; }
    public Nullable<int> Location_ID { get; set; }
    public Nullable<System.DateTime> BegginingDate { get; set; }
    public string nTrain { get; set; }
    public string Content { get; set; }

    public virtual ICollection<Comment> Comments { get; set; }
    public virtual Conference Conference { get; set; }
    public virtual ICollection<Rate> Rates { get; set; }
    public virtual ICollection<RawDate> RawDates { get; set; }
    public virtual EventType EventType { get; set; }
    public virtual Location Location { get; set; }
}

当我调用web api post方法时,标题中提到的异常将被抛出:

var response = await client.PostAsJsonAsync("api/event", event);

我在Event类的每个虚拟字段上方添加了[JsonIgnore]。这次序列化工作,但忽略的字段没有序列化,它们的值为null。我真的需要Event对象中包含的所有信息。我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

在WebAPIConfig.cs中添加以下配置可以解决该错误。

var json = config.Formatters.JsonFormatter;
//Below configuration to mandatory to resolve the Self referencing loop detected with       
"Newtonsoft.Json.JsonSerializationException" ,
json.SerializerSettings.PreserveReferencesHandling =    
Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);

答案 1 :(得分:0)

循环引用对象不能进行JSON序列化。我建议您使用一个视图模型,在该模型中您将包含所需的属性,然后让您的操作返回此视图模型而不是实际的域模型。