Deserializing such that a field is an empty list rather than null

前端 未结 2 578
天命终不由人
天命终不由人 2021-01-11 14:38

If I have a class like this:

[DataContract(Name = \"\", Namespace = \"\")]
public class MyDataObject
{
    [DataMember(Name = \"NeverNull\")]
    public ILis         


        
相关标签:
2条回答
  • 2021-01-11 15:04

    Initialization of IList<int>with new int[0] will help you out! Its the solution that gives me the best results.

    0 讨论(0)
  • 2021-01-11 15:16

    Perhaps add a post-serialization callback that checks this at the end of deserialization?

    [DataContract(Name = "", Namespace = "")]
    public class MyDataObject
    {
        [OnDeserialized]
        public void OnDeserialized(StreamingContext context)
        {
            if (MyInts == null) MyInts = new List<int>();
        }
        [DataMember(Name = "NeverNull")]
        public IList<int> MyInts { get; set; }
    }
    

    Note also that JsonConvert (unlike DataContractSerializer) executes the default constructor, so usually you could also have just added a default constructor:

        public MyDataObject()
        {
            MyInts = new List<int>();
        }
    

    however, in this case the explict "NeverNull":null changes it back to null during deserialization, hence why I've used a callback above instead.

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