项目类型:asp.net mvc 4
有如下类:
public class Category { public Category() { Products = new List<Product>(); } public int Id { get; set; } public string Name { get; set; } public ICollection<Product> Products { get; set; } } public class Product { public int Id { get; set; } public string Name { get; set; } public virtual Category Category { get; set; } }
contoller:
Category c1 = new Category() { Id = 1, Name = "c1" }; Product p1 = new Product() { Id=10, Name="p10", Category=c1 }; Product p2 = new Product() { Id = 20, Name = "p20", Category=c1 }; c1.Products.Add(p1); c1.Products.Add(p2); return Json(c1, JsonRequestBehavior.AllowGet);
我在WebApiConfig中加了如下代码,但是不管用:
// Fix 1 config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; // Fix 2 //config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling // = Newtonsoft.Json.ReferenceLoopHandling.Serialize; //config.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling // = Newtonsoft.Json.PreserveReferencesHandling.Objects; //config.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling // = Newtonsoft.Json.PreserveReferencesHandling.All;
我又用Newtonsoft.Json原生的JsonConvert去试,发现是可以的:
JsonSerializerSettings setting = new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }; var ret= JsonConvert.SerializeObject(c1, setting);
现在可以确定问题所在为:configuration中的那个设置根本就没起效,求救,怎么让那个该死的设置起效
检查一下有这个吗? :
protected void Application_Start(){
WebApiConfig.Register(GlobalConfiguration.Configuration);
}
在Application_Start()中,是调用了WebApiConfig.Register(GlobalConfiguration.Configuration)方法的
这个时候就不能直接序列化了,最好就是在定义一个实体,把两个表的属性都放里面,序列化这个实体即可。同时这样也符合ViewModel的独立性,不直接依赖与数据库实体。