Make JSON.NET and Serializable attribute work together

前端 未结 3 808
刺人心
刺人心 2020-12-28 16:25

I\'m using JSON.NET and had some troubles in the past during WEBAPI objects deserialization. After doing some research I\'ve found that the class was marked with [Serializab

3条回答
  •  一向
    一向 (楼主)
    2020-12-28 17:12

    I was using a POCO with Serializable attribute. In the first case while Posting Request to a WebApi worked by using the following method:

    JsonMediaTypeFormatter f = new JsonMediaTypeFormatter()
    {
        SerializerSettings = new JsonSerializerSettings()
        {
            ContractResolver = new DefaultContractResolver()
            {
                IgnoreSerializableAttribute = true
            }
        }
    };
    
    var result = client.PostAsJsonAsync>("company/savecompanies", companies).Result;
    
    //I have truncated the below class for demo purpose
    [Serializable]
    public class Company
    {
        public string CompanyName {get;set;}
    }
    

    However, when I tried to read the response from WebApi (Which was posted back as JSON), the object was not properly deserialized. There was not error, but property values were null. The below code did not work:

    var readObject = result.Content.ReadAsAsync>().Result;
    

    I read the documentation as given on Newtonsoft.Json website https://www.newtonsoft.com/json/help/html/SerializationAttributes.htm and found the following and I quote from that site:

    Json.NET attributes take precedence over standard .NET serialization attributes (e.g. if both JsonPropertyAttribute and DataMemberAttribute are present on a property and both customize the name, the name from JsonPropertyAttribute will be used).

    So, it was clear if Newtonsoft.Json attributes are present before the standard .NET attributes they will take precedence. Hence I could use the same class for two purposes. One, when I want to post to a WebApi, Newtonsoft Json serializer will kick in and Two, when I want to use BinaryFormatter.Serialize() method std .NET Serializable attribute will work.

    The same was confirmed with the answer given above by @Javier. So I modified the Company Class as under:

    [JsonObject]
    [Serializable]
    public class Company
    {
        public string CompanyName {get;set;}
    }
    

    I was able to use the same class for both purposes. And there was no need for the below code:

    JsonMediaTypeFormatter f = new JsonMediaTypeFormatter()
    {
        SerializerSettings = new JsonSerializerSettings()
        {
            ContractResolver = new DefaultContractResolver()
            {
                IgnoreSerializableAttribute = true
            }
        }
    };
    

提交回复
热议问题