在WebAPI中使用Model上的Serializable属性

时间:2015-04-30 07:52:10

标签: c# json asp.net-web-api serializable

我有以下场景:我正在使用WebAPI并根据模型将JSON结果返回给使用者。我现在还需要将模型序列化为base64,以便能够将它们保存在缓存中和/或将它们用于审计目的。问题是,当我将[Serializable]属性添加到模型以便将模型转换为Base64时,JSON输出更改如下:

模特:

[Serializable]
public class ResortModel
{
    public int ResortKey { get; set; }

    public string ResortName { get; set; }
}

没有[Serializable]属性,JSON输出为:

{
    "ResortKey": 1,
    "ResortName": "Resort A"
}

使用[Serializable]属性,JSON输出为:

{
    "<ResortKey>k__BackingField": 1,
    "<ResortName>k__BackingField": "Resort A"
}

如何在不更改JSON输出的情况下使用[Serializable]属性?

1 个答案:

答案 0 :(得分:29)

默认情况下,Json.NET忽略#alert{position:absolute;top:0;left:0;right:0;bottom:0;margin:0;width:600px;height:250px;background:#CCE6FF;border:1px solid #a1a1a1;margin:auto;overflow-y:auto;} #close{padding:5px; background:blue;color:white;border-radius:5px;cursor: pointer;}属性。但是,根据this answerMaggie Ying的评论(下面引用,因为评论并不意味着持续),WebAPI会覆盖导致输出的行为。

  

默认情况下,Json.NET序列化程序将IgnoreSerializableAttribute设置为true。在WebAPI中,我们将其设置为false。您遇到此问题的原因是因为Json.NET忽略了属性:“Json.NET现在检测具有Seri​​alizableAttribute的类型并序列化该类型的所有字段,包括公共和私有,并忽略属性”(引自{{ 3}})

在没有WebAPI的情况下演示相同行为的简单示例可能如下所示:

Serializable

有几种解决此问题的方法。一种是使用普通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; } } 中的默认设置。根据{{​​3}},默认设置应该这样做:

Application_Start()

如果这不起作用,你可以明确说明:

GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings = new Newtonsoft.Json.JsonSerializerSettings();