Parameters[0].Name
is a
JValue
. Specifically it's the string "ESPN" given the example JSON.
JValue
has implementations for converting common types like strings so you can do
(string)jValueThatIsAString
. But the value in your example will never be a
JArray
which is why you get the error.
I'm not really sure what you mean by "nested and un-nested" since there are no nesting differences in your sample JSON. I'm guessing you want to be able to aggregate all Name properties of objects in an array. You can do it like this:
JToken token = JToken.Parse(@"
{
""OperationID"": 7,
""Outcome"": 0,
""Parameters"": [
{
""Name"": ""ESPN"",
""Value"": ""342.342.444"",
""VariableType"": ""System.String""
},
{
""Name"": ""source"",
""Value"": ""0"",
""VariableType"": ""ServiceData.Contracts.Validation.Source""
}
]
}");
IEnumerable<string> entries = token
.SelectToken("Parameters")
.Select(p => (string)p.SelectToken("Name"));
IEnumerable<JToken> entries = token.
.SelectToken("Parameters")
.Select(p => p.SelectToken("Name"));
IEnumerable<JToken> entries = token.SelectTokens("$.Parameters[*].Name");
IEnumerable<JToken> entries = token.SelectTokens("$.Parameters[*]");
References:
Newtonsoft.Json.Linq Namespace[
^]
LINQ to JSON[
^]
JSONPath - XPath for JSON[
^]
EDIT: For fun, if you do have objects with a Name property arbitrarily nested within an array called Parameters that can contain subarrays, you could retrieve all Name properties using this:
IEnumerable<JToken> entries = token.SelectTokens("$.Parameters..Name");
IEnumerable<JToken> entries = token.SelectTokens("$.Parameters[*]..Name");
This works regardless of the nesting depth of the subarrays or objects.