默认情况下,Json.NET 会忽略Serializable
属性。然而,根据评论这个答案 https://stackoverflow.com/a/12844557/2700399 by 应玛吉 https://stackoverflow.com/users/1672536/maggie-ying(在下面引用是因为注释并不意味着持久),WebAPI 会覆盖该行为,从而导致您的输出。
Json.NET 序列化程序默认将 IgnoreSerializedAttribute 设置为 true。在 WebAPI 中,我们将其设置为 false。您遇到此问题的原因是因为 Json.NET 忽略属性:“Json.NET 现在检测具有 SerializedAttribute 的类型,并序列化该类型上的所有字段(公共和私有),并忽略属性”(引自james.newtonking.com/archive/2012/04/11/… http://james.newtonking.com/archive/2012/04/11/json-net-4-5-release-2-serializable-support-and-bug-fixes)
一个简单的例子在没有 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()
。根据这个答案 https://stackoverflow.com/a/11421486/2700399,默认设置应该可以做到这一点:
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings = new Newtonsoft.Json.JsonSerializerSettings();
如果这不起作用,您可以明确说明:
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings()
{
ContractResolver = new DefaultContractResolver()
{
IgnoreSerializableAttribute = true
}
};