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

好久不见. 提交于 2019-12-10 01:52:10

问题


If I have a class like this:

[DataContract(Name = "", Namespace = "")]
public class MyDataObject
{
    [DataMember(Name = "NeverNull")]
    public IList<int> MyInts { get; set; }
}

Is there a way I can make MyInts field a non-null empty list when the following string is deserialized?

string serialized = @"{""NeverNull"":null}";

MyDataObject myDataObject = JsonConvert.DeserializeObject<MyDataObject>(serialized);

I’m using Newtonsoft.Json

The reason I ask is that I have a fairly complicated json request to parse, it contains nests of lists of objects and I'd like the deserialization code to create these object so I can avoid lots of null checks:

if (foo.bar != null)
{
    foreach (var bar in foo.bar)
    {
        if (bar.baz != null)
        {
            foreach (var baz in bar.baz)
            {
                ...

回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/11946531/deserializing-such-that-a-field-is-an-empty-list-rather-than-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!