I'm using Newtonsoft to deserialize an known JSON object and retrieve some values from it if they're present.
The crux is there is that object structure may keep changing so I'm using dynamic to traverse the structure and retrieve the values. Since the object structure keeps changing, I'm using the null conditional operator to traverse the JSON.
The code looks like this
dynamic jsonMeta = JsonConvert.DeserializeObject<dynamic>(jsonScript);
string gVal = jsonMeta.a?.b?.c?.d?.e?.f?.g?.Value ?? ""
The whole idea of this is to traverse the object in a null safe manner so that if a member doesn't exist, it evaluates to null
and it assigns it a default value without throwing an exception. But what I'm seeing is that I get a exception 'Newtonsoft.Json.Linq.JValue' does not contain a definition for 'e'
if that member d is null
.
My understanding is that while the Value of d
is null
, it's of type JValue
so that's why the null conditional operator doesn't work, but then it tries to access member e
inside d
it throws the exception.
So my question is how can I make this work in C#? Is there an easy way to access the JSON members without knowing the JSON structure in a single line or relatively easy way?
SelectToken()
. – StylographSelectToken
again doesn't seem to check each member against anull
from your example above. The idea is to check each member against anull
value since any of them could potentially be anull
at runtime and we don't know to end up with an exception, but instead handle it gracefully for each member if the structure has anull
anywhere in the chain. – Strother