2

Seems like a bug to me.

var obj = JsonConvert.DeserializeObject<dynamic>("{\"arr\": [{\"prop1\": null}]}");
var prop1 = ob.arr[0].prop1; // has {} value
var test = ob.arr[0].prop1?.prop2; //causes error 

'Newtonsoft.Json.Linq.JValue' does not contain a definition for 'prop2'

Stephen Kennedy
  • 20,585
  • 22
  • 95
  • 108
Toolkit
  • 10,779
  • 8
  • 59
  • 68
  • Where should JsonConvert could get information about prop2? You are using dynamic, there is no structure definition with prop2. – Karel Kral Feb 10 '19 at 12:15
  • if json is like thios `{\"obj\": {\"prop1\": null}}` everything is fine – Toolkit Feb 10 '19 at 12:36
  • Related or duplicate: [string behavior in json.net: why is a null JToken replaced with a non-null value?](https://stackoverflow.com/q/51776584/3744182) and [Newtonsoft Json.Net serialize JObject doesn't ignore nulls, even with the right settings](https://stackoverflow.com/a/29259032/3744182) and [Null-coalescing operator returning null for properties of dynamic objects](https://stackoverflow.com/a/29053805/3744182). – dbc Feb 10 '19 at 22:27

1 Answers1

2

ob.arr[0].prop1 is not null (it is a non-null empty JValue), so the null coalescing operator doesn't halt the access chain.

Instead ob.arr[0].prop1.Value is null, so you may use:

var test = obj.arr[0].prop1.Value?.prop2;

or

var test = obj.arr[0].prop1.HasValues
  ? obj.arr[0].prop1.prop2 // this will be null in your case
  : null;
didymus
  • 250
  • 2
  • 9
  • so what is the difference between `"{'arr': [{'prop1': null}]}"` and `"{'obj': {'prop1': null}}"`? Why `prop1` is `{}` in the first case and `null` in the second? – Toolkit Feb 10 '19 at 20:37
  • @Toolkit, I get `{}` in both cases. For `var obj = JsonConvert.DeserializeObject("{'arr': [{'prop1': null}]}");`, `obj.arr[0].prop1` is `{}`. For `var obj = JsonConvert.DeserializeObject("{'obj': {'prop1': null}}");`, `obj.obj.prop1` is `{}` – didymus Feb 10 '19 at 23:46
  • no it's wrong, if no array is present, null coalescing operator works fine, sorry wrong answer, not sure why people upvote – Toolkit Feb 17 '19 at 17:25