Newtonsoft.Json
Newtonsoft.Json copied to clipboard
Null properties do not play well with dynamic and null propagation/null coalescing operators
I have this code:
dynamic obj = JsonConvert.DeserializeObject("{ \"a\": null }");
CASE 1:
I'm trying to use null propagation operator:
var c = obj.a?.b;
The expected result is to have 'c' equal null. But, in reality the following exception is thrown:
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'Newtonsoft.Json.Linq.JValue' does not contain a definition for 'b'
CASE 2:
I'm trying to use null coalescing operator:
var c = obj.a ?? 666;
The expected result is to have value '666' in the variable 'c'. In reality, it contains a JValue with Type.Null.
Hovewer, this:
var c = obj.b ?? 666;
produces expected result.
CONCLUSION:
To me, both of thess cases seem to produce very unexpected, non-intuitive behavior and are highly confusing for the reader of the code. Also, it is pretty hard to spot these issues. What this means is that to avoid such pitfalls we should stop using dynamic in conjunction with Newtonsoft.Json altogether. And that is not what many people would like to do :).
So, may be i'm missing something here and there are known ways to make this work as expected. Well, I know that I can traverse my JToken and remove all JValues with Type.Null, but that is a crazy thing to do in my opinion.
Second this, it would be nice to have it play well with null conditional operators