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

Viewed 5085

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)
            {
                ...
2 Answers
Related