我了解 ASP.NET Web API 本身使用 Json.NET 来(反)序列化对象,但是有没有办法指定JsonSerializerSettings您希望它使用的对象?
例如,如果我想type在序列化的 JSON 字符串中包含信息怎么办?通常我会在调用中注入设置.Serialize(),但 Web API 会默默地做到这一点。我找不到手动注入设置的方法。
我了解 ASP.NET Web API 本身使用 Json.NET 来(反)序列化对象,但是有没有办法指定JsonSerializerSettings您希望它使用的对象?
例如,如果我想type在序列化的 JSON 字符串中包含信息怎么办?通常我会在调用中注入设置.Serialize(),但 Web API 会默默地做到这一点。我找不到手动注入设置的方法。
您可以JsonSerializerSettings使用对象Formatters.JsonFormatter.SerializerSettings中的属性来自定义HttpConfiguration。
例如,您可以在 Application_Start() 方法中执行此操作:
protected void Application_Start()
{
HttpConfiguration config = GlobalConfiguration.Configuration;
config.Formatters.JsonFormatter.SerializerSettings.Formatting =
Newtonsoft.Json.Formatting.Indented;
}
您可以JsonSerializerSettings为每个指定JsonConvert,并且可以设置全局默认值。
单JsonConvert重载:
// Option #1.
JsonSerializerSettings config = new JsonSerializerSettings { ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore };
this.json = JsonConvert.SerializeObject(YourObject, Formatting.Indented, config);
// Option #2 (inline).
JsonConvert.SerializeObject(YourObject, Formatting.Indented,
new JsonSerializerSettings() {
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
}
);
Application_Start()Global.asax.cs中带有代码的全局设置:
JsonConvert.DefaultSettings = () => new JsonSerializerSettings {
Formatting = Newtonsoft.Json.Formatting.Indented,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
};
答案是将这 2 行代码添加到 Global.asax.cs Application_Start 方法
var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling =
Newtonsoft.Json.PreserveReferencesHandling.All;
参考:处理循环对象引用