Reputation: 2165
I have a dynamic JSON string (the structure can change depending on the content sent by the server). I'm deserializing it using Newstonsoft.Json
as a dynamic ExpandoObject
dynamic jsonMeta = JsonConvert.DeserializeObject<ExpandoObject>(jsonScript, new ExpandoObjectConverter());
The reason I'm using a dynamic ExpandoObject
is because it's supposed to allow me the flexibility to work with a non-fixed JSON structure.
I'm trying to access a property called (e.g. plot) which may or may not exist:
string plot = jsonMeta.plot
The problem I'm facing is that when plot
does not exist in the JSON string, I'm expecting it to return a 'null' but instead it's throwing an exception:
'System.Dynamic.ExpandoObject' does not contain a definition for 'plot' Microsoft.CSharp.RuntimeBinder.RuntimeBinderException
How can I get it to return a null
instead of throwing an exception when it encounters a property that doesn't exist?
I'm would prefer not trying to check for the existence of the property as it would cause extreme code bloat since my goal is to use a nested null conditional operator like jsonMeta.plot?.name?.text
Is it possible to override or change the ExpandoObject behavior? If there's a cleaner way to handler this situation I'm open to considering it (not tied to ExpandoObject or Newtonsoft.Json).
EDIT: Someone marked this as a duplicate of this question. It's quite different, it's not about how to deserialize an anonymous JSON, but rather about how to not to get an exception when accessing properties in an anonymous deserialized JSON (using ExpandoObject or any other means).
Upvotes: 0
Views: 305
Reputation: 9620
The ExpandoObject is effectively just a dictionary. So you can use a dictionary instead.
Dictionary<string,object?> jsonMeta = JsonConvert.DeserializeObject<Dictionary<string,object?>>(jsonScript);
So then you can simply check for an existing key, and perform your work based on this.
if (jsonMeta.ContainsKey("plot"))
{
string plot = jsonMeta["plot"] as string;
}
Upvotes: 0