Ric*_*gan 68 c# json.net asp.net-web-api
我知道ASP.NET Web API本身使用Json.NET来(反)序列化对象,但有没有办法指定JsonSerializerSettings你想要它使用的对象?
例如,如果我想将type信息包含在序列化的JSON字符串中该怎么办?通常我会在.Serialize()调用中注入设置,但Web API会默默地执行此操作.我找不到手动注入设置的方法.
car*_*ira 107
您可以JsonSerializerSettings使用对象中的Formatters.JsonFormatter.SerializerSettings属性自定义HttpConfiguration.
例如,您可以在Application_Start()方法中执行此操作:
protected void Application_Start()
{
HttpConfiguration config = GlobalConfiguration.Configuration;
config.Formatters.JsonFormatter.SerializerSettings.Formatting =
Newtonsoft.Json.Formatting.Indented;
}
Run Code Online (Sandbox Code Playgroud)
smo*_*kle 36
您可以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
}
);
Run Code Online (Sandbox Code Playgroud)
Application_Start()Global.asax.cs中代码的全局设置:
JsonConvert.DefaultSettings = () => new JsonSerializerSettings {
Formatting = Newtonsoft.Json.Formatting.Indented,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
};
Run Code Online (Sandbox Code Playgroud)
参考:https://github.com/JamesNK/Newtonsoft.Json/issues/78
| 归档时间: |
|
| 查看次数: |
91565 次 |
| 最近记录: |