【发布时间】:2014-01-29 13:50:55
【问题描述】:
我似乎无法阻止 Web API/JSON.NET 在序列化对象时使用 Newtonsoft.Json.PreserveReferencesHandling.Objects。换句话说,尽管使用了以下设置,但 $id/$ref 始终在序列化对象中使用:
public class MvcApplication : System.Web.HttpApplication {
protected void Application_Start () {
WebApiConfig.Register(GlobalConfiguration.Configuration);
}
}
public static class WebApiConfig {
public static void Register (HttpConfiguration config) {
JsonMediaTypeFormatter jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().Single();
jsonFormatter.UseDataContractJsonSerializer = false;
jsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
jsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
jsonFormatter.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.None;
}
}
有什么想法吗?
【问题讨论】:
-
在
WebApiConfig类中设置这个(public static void Register (HttpConfiguration config)从 Global.asax.cs 中的protected void Application_Start ()调用 -
根据下面@AndreHaverdings 的回答,将 PreserveReferencesHandling 设置为 All 会导致添加 id 和引用。将最后一行设置为
jsonFormatter.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.None;应该可以解决问题。
标签: c# asp.net-mvc-4 json.net asp.net-web-api