我似乎无法阻止 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;
}
}
有什么想法吗?
最佳答案
将其放入 Global.asax 中以配置引用处理。 PreserveReferencesHandling 不应为“全部”
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.None;
关于c# - 使用 Web API 和 JSON.NET 序列化对象时防止 $id/$ref,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21046872/