Reputation: 14385
I am using JSON.net in a C# Windows Form application to deserialize a JSON string to a dynamic object:
dynamic jsonObj = JsonConvert.DeserializeObject(strJson);
I'm using the following test JSON for testing:
{"payload":"thePayload","number":3,"dialogResult":"one"}
When I run the code, I can indeed access the properties of the dynamic object using an associative array approach:
var x = jsonObj["payload"];
However, if I try to access the content using property names:
var x = jsonObj.payload;
It works but I get the following Exception:
A first chance exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in Microsoft.CSharp.dll
Is there a way to change things so I can access the deserialized content in the dynamic object using property names instead of as an associative array, without getting the exception?
I found this SO post on RutimeBinderExceptions:
Accessing properties of anonymous/dynamic types across dll boundaries gives RuntimeBinderException
But I'd prefer not to use the ExpandoObject type and I'm not even sure if it applies to my situation.
UPDATE: Ok, I believe I am having the problem of depicted in the reference SO post above. The context of the call is a callback from the CefSharp browser user control when Javascript calls back into my C# app.
Upvotes: 2
Views: 1426
Reputation: 371
Try working without the dynamic
data type:
Dictionary<string, object> theData= new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(jsonString);
string payload = (string)theData["payload"];
int number = (int)theData["number"];
string dialogResult = (string)theData["dialogResult"];
The call to Deserialize() creates a tree of Dictionary that you can traverse at will.
Upvotes: 3