Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)
            {
                ...
like image 515
s d Avatar asked Aug 14 '12 05:08

s d


1 Answers

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.

like image 104
Marc Gravell Avatar answered Nov 13 '22 15:11

Marc Gravell