Web Api不会序列化我的对象图

时间:2013-01-05 19:56:05

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

我有两个简单的实体:

public class Ingredient : IEntity
{
    public Ingredient()
    {
        Drinks = new List<Drink>();
    }

    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Drink> Drinks { get; set; }
}

public class Drink : IEntity
{
    public Drink()
    {
        Ingridients = new List<Ingredient>();
    }

    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Ingredient> Ingridients { get; set; }
    public string Approach { get; set; }
}

我收到以下错误:

Object graph for type 'Gudo.Core.Model.Ingredient' contains cycles and cannot be serialized if reference tracking is disabled.

我尝试使用JsonIgnore集合上的Drinks属性,我尝试过使用:

JsonSerializerSettings jsSettings = new JsonSerializerSettings();
        jsSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;

在我的global.asax

没有任何作用..

请帮忙。

1 个答案:

答案 0 :(得分:1)

您确定在JSON格式化程序的序列化程序设置上设置了此项吗?这一行应该为你做到:

GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;