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'

3

1 Answer 1

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;
Sign up to request clarification or add additional context in comments.

3 Comments

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, I get {} in both cases. For var obj = JsonConvert.DeserializeObject<dynamic>("{'arr': [{'prop1': null}]}");, obj.arr[0].prop1 is {}. For var obj = JsonConvert.DeserializeObject<dynamic>("{'obj': {'prop1': null}}");, obj.obj.prop1 is {}
no it's wrong, if no array is present, null coalescing operator works fine, sorry wrong answer, not sure why people upvote

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.