简体   繁体   English

如何获取通用字典中的值?

[英]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.
}

Use JSON .Net , then simply: 使用JSON .Net ,然后简单地:

JObject dynJson = JObject.Parse(jsonString);

followed by: 其次是:

string data = dynJson["popup"]["position"];

JObject.Parse JObject.Parse

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM