[英]How do I get the value in a generic Dictionary?
I have a json
string like this: 我有一个像这样的json
字符串:
{
"ipaddress": "xxx",
"hostname": "comcast.xxx",
"popup": {
"position": "1256",
"pagename": "home"
}
}
In my Windows Form code I've been using JavaScriptSerializer
for phare those line to dictionary. 在我的Windows窗体代码中,我一直在使用JavaScriptSerializer
来将那些行转换为字典。
var obj = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(json);
It is working fine at the moment, but I don't know how to get value inside popup
? 目前工作正常,但我不知道如何在popup
内获得价值? Because it's another dictionary. 因为这是另一本字典。
[7] = {[popup, System.Collections.Generic.Dictionary`2[System.String,System.Object]]}
The fastest (yet unsafe) way of doing it is like this is via the indexer: 这样做的最快(但不安全)方式是通过索引器:
First extract the first dictionary and cast, since the first dictionary will yield an object of type object
: 首先提取第一个字典并进行转换,因为第一个字典将产生一个object类型的object
:
var popup = (Dictionary<string, object>)obj["popup"];
Then, you extract the values based on keys: 然后,您基于键提取值:
var position = popup["position"];
var pagename = popup["pagename"];
If you're not sure both keys will exist in the result, you can use Dictionary.TryGetValue
if they exist: 如果您不确定结果中是否存在两个键,则可以使用Dictionary.TryGetValue
如果存在):
obj position;
if (!popup.TryGetValue("position", out position))
{
// Key isn't in the dictionary.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.