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

后端 未结 2 1896
囚心锁ツ
囚心锁ツ 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
    {
        /// <summary>
        /// The document type that the concrete class expects to be deserialized from.
        /// </summary>
        //[JsonProperty(PropertyName = "DocumentType")] // We substitute the DocumentType property with this ExpectedDocumentType property when serializing derived types.
        public abstract string ExpectedDocumentType { get; }
    
        /// <summary>
        /// The actual document type that was provided in the JSON that the concrete class was deserialized from.
        /// </summary>
        public string DocumentType { get; set; }
    
        //Tells json.net to not serialize DocumentType, but allows DocumentType to be deserialized
        public bool ShouldSerializeDocumentType()
        {
            return false;
        }
    }
    
    0 讨论(0)
  • 2020-12-22 01:10

    You can do this with an Enum, I don't know if DocumentType is a enum but it should.

    enum DocumentType {
        XML,
        JSON,
        PDF,
        DOC
    }
    

    When deserializing the request it will give you an error if the client sends you an invalid enum. The "InvalidEnumArgumentException" which you can catch and tell the client that it's sending an non valid DocumentType.

    0 讨论(0)
提交回复
热议问题