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)
{
...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With