Using the Serializable Attribute for a Model in WebAPI

I have the following scenario: I use WebAPI and return JSON results for the consumer based on the model. Now I have an additional requirement for serializing models for base64 in order to be able to store them in the cache and / or use them for audit purposes. The problem is that when I add the [Serializable] attribute to the model, so to convert the model to Base64, the JSON output changes as follows:

Model:

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

Without the attribute [Serializable] JSON output:

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

With the [Serializable] attribute, JSON output:

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

How can I use the [Serializable] attribute without changing the JSON output?

+6
source share
1 answer

By default, Json.NET ignores the Serializable attribute. However, according to the commentary, this answer is from Maggie Ying ( given below because the comments are not meant to be continued), the WebAPI overrides this behavior that causes your output.

The Json.NET serial analyzer sets the IgnoreSerializableAttribute parameter to true by default. In WebAPI, we set to false. The reason you ran into this problem is because Json.NET ignores properties: "Json.NET now detects types that have SerializableAttribute, and serializes all fields of this type, both public and private, and ignores properties "(quoted from james.newtonking.com/archive/2012/04/11 / ... )

A simple example showing the same behavior without a WebAPI might look like this:

 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 } })); } } } 

There are several ways around this behavior. One is to decorate your model with a simple JsonObject attribute:

 [Serializable] [JsonObject] class Foo { public string Bar { get; set; } } 

Another way is to override the default settings in Application_Start() . According to this answer , the default settings should do this:

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

If this does not work, you may be explicit:

 GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings() { ContractResolver = new DefaultContractResolver() { IgnoreSerializableAttribute = true } }; 
+22
source

Source: https://habr.com/ru/post/986276/


All Articles