[英]Deserialized JSON object to dynamic type but getting RuntimeBinderException accessing properties?
I am using JSON.net in a C# Windows Form application to deserialize a JSON string to a dynamic object: 我在C#Windows Form应用程序中使用JSON.net将JSON字符串反序列化为动态对象:
dynamic jsonObj = JsonConvert.DeserializeObject(strJson);
I'm using the following test JSON for testing: 我正在使用以下测试JSON进行测试:
{"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: 我在RutimeBinderExceptions上找到了这样的帖子:
Accessing properties of anonymous/dynamic types across dll boundaries gives RuntimeBinderException 跨DLL边界访问匿名/动态类型的属性会给出RuntimeBinderException
But I'd prefer not to use the ExpandoObject type and I'm not even sure if it applies to my situation. 但是我不希望使用ExpandoObject类型,并且甚至不确定它是否适用于我的情况。
UPDATE: Ok, I believe I am having the problem of depicted in the reference SO post above. 更新:好的,我相信我在上面的参考SO帖子中描述了问题。 The context of the call is a callback from the CefSharp browser user control when Javascript calls back into my C# app.
调用的上下文是当Javascript回调到我的C#应用程序时,来自CefSharp浏览器用户控件的回调。
Try working without the dynamic
data type: 尝试不使用
dynamic
数据类型:
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. 对Deserialize()的调用会创建一棵词典树,您可以随意遍历它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.