默认情况下,Json.NET会忽略该
Serializable属性。不过,根据要评论此答案由张曼玉颖,覆盖的WebAPI这种行为,这会导致你的输出。
默认情况下,Json.NET序列化程序将IgnoreSerializableAttribute设置为true。在WebAPI中,我们将其设置为false。遇到此问题的原因是Json.NET忽略了属性:“
Json.NET现在检测到具有SerializableAttribute的类型,并对该类型上的所有字段(包括公共字段和私有字段)进行序列化,并忽略属性”(引自james。
newtonking.com/archive/2012/04/11/…)
一个简单的示例演示没有WebAPI时的相同行为,如下所示:
using Newtonsoft.Json;using Newtonsoft.Json.Serialization;using System;namespace Scratch{ [Serializable] class Foo { public string Bar { get; set; } } class Program { static void Main() { var foo = new Foo() { Bar = "Blah" }; Console.WriteLine(JsonConvert.SerializeObject(foo, new JsonSerializerSettings() { ContractResolver = new DefaultContractResolver() { IgnoreSerializableAttribute = false } })); } }}有几种方法可以解决此问题。一种是用普通
JsonObject属性装饰模型:
[Serializable][JsonObject]class Foo{ public string Bar { get; set; }}另一种方法是覆盖的默认设置
Application_Start()。根据此答案,默认设置应执行以下操作:
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings = new Newtonsoft.Json.JsonSerializerSettings();
如果那不起作用,您可以明确地知道它:
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings() { ContractResolver = new DefaultContractResolver() { IgnoreSerializableAttribute = true } };


