Null-coalescing operator in conjuction with JObject

1

I have below code written to read JArray from a given JObject.

To my understanding, when the value of "tags" in JObject is null, IEnumerable should be initialized as empty.

IEnumerable<string> tags = eventPayload?["tags"]?.Values<string>() ?? Enumerable.Empty<string>();

However, this lines throws exception when json looks like

{
    "tags": null   
}

System.InvalidOperationException
  HResult=0x80131509
  Message=Cannot access child value on Newtonsoft.Json.Linq.JValue.

If I were to make above line read null and initialize enumerable as empty, what changes do I need to make?

c#
json
json.net
null-coalescing-operator
null-coalescing
asked on Stack Overflow Sep 26, 2018 by Evan Park • edited Sep 26, 2018 by Erik Philips

1 Answer

2

The issue is that eventPayload?["tags"] is JValue.Null, not null.

answered on Stack Overflow Sep 26, 2018 by Eugene Shvets

User contributions licensed under CC BY-SA 3.0