JSON.Net - Use JsonIgnoreAttribute only on serialization (But not when deserialzing)

后端 未结 2 1922
囚心锁ツ
囚心锁ツ 2020-12-22 00:22

We\'re using JSON.net and want to use a consistent way to send and receive data (documents).

We want a base class that all documents will be derived from. The base c

2条回答
  •  佛祖请我去吃肉
    2020-12-22 01:05

    Use the ShouldSerialize feature provided by Json.Net. So basically, your class will look like:

    public abstract class JsonDocument
    {
        /// 
        /// The document type that the concrete class expects to be deserialized from.
        /// 
        //[JsonProperty(PropertyName = "DocumentType")] // We substitute the DocumentType property with this ExpectedDocumentType property when serializing derived types.
        public abstract string ExpectedDocumentType { get; }
    
        /// 
        /// The actual document type that was provided in the JSON that the concrete class was deserialized from.
        /// 
        public string DocumentType { get; set; }
    
        //Tells json.net to not serialize DocumentType, but allows DocumentType to be deserialized
        public bool ShouldSerializeDocumentType()
        {
            return false;
        }
    }
    

提交回复
热议问题