How to handle null/empty values in JsonConvert.DeserializeObject

后端 未结 4 705
执笔经年
执笔经年 2020-12-12 22:52

I have the following code:

return (DataTable)JsonConvert.DeserializeObject(_data, (typeof(DataTable)));

Then, I tried:

var          


        
4条回答
  •  自闭症患者
    2020-12-12 23:22

    An alternative solution for Thomas Hagström, which is my prefered, is to use the property attribute on the member variables.

    For example when we invoke an API, it may or may not return the error message, so we can set the NullValueHandling property for ErrorMessage:

    
        public class Response
        {
            public string Status;
    
            public string ErrorCode;
    
            [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
            public string ErrorMessage;
        }
    
    
        var response = JsonConvert.DeserializeObject(data);
    

    The benefit of this is to isolate the data definition (what) and deserialization (use), the deserilazation needn’t to care about the data property, so that two persons can work together, and the deserialize statement will be clean and simple.

提交回复
热议问题