【问题标题】:How to iterate through list of generic dictionary in C#如何遍历C#中的通用字典列表
【发布时间】:2013-05-16 08:45:43
【问题描述】:

我有一个 json 对象,它被转换为字典列表。 json如下:

{
"DataList":
{"Non Fuel":
{
   "sn":"/DataXmlProduct/Customers/DataXml/Customer/DueDate",
   "ItemCode":"/DataXmlProduct/Customers/DataXml/Customer/InvoiceNo",
   "Qty":"/DataXmlProduct/Customers/DataXml/Customer/CustomerNo",
   "Amount":"DataXml/Customer/TotalCurrentCharges"
  },

  "Fuel":{
   "sn":"/DataXmlProduct/Customers/DataXml/Customer/InvoiceNo",
   "ItemCode":"/DataXmlProduct/Customers/DataXml/Customer/InvoiceNo",
   "Amount":"DataXml/Customer/TotalCurrentCharges"
  }
 }
}

结果是(Dictionary<string, object>),这里每个字典的值又是一个字典,我需要动态迭代字典的每个值并获取最后一个键和值,其中值为 Xpath,需要从 xpath 获取值。 请帮助我找到遍历字典的解决方案。它应该是通用的,因为 json 格式可以根据用户输入而变化。

【问题讨论】:

    标签: c# json dictionary


    【解决方案1】:

    假设实际值(例如fuel 的内容)以KeyValuePair<string, object> 的形式出现,那么您可以使用递归方法:

    public static void ParseData(object source)
    {
        Dictionary<string, object> Dict;
        KeyValuePair<string, object> Kvp;
        if ((Dict = source as Dictionary<string,object>) != null)
        {
            foreach(var kvp in Dict)
            {
                Console.WriteLine(kvp.Key);
                ParseData(kvp.Value);
            }
        }
        elseif ((Kvp = source as KeyValuePair<string, object>) != null)
        {
            Console.WriteLine("{0}{1}", Kvp.Key, Kvp.Value);
        }
    }
    

    这做了一个或两个假设,但这将遍历所有数据,假设它由字典和 kvps 组成。

    编辑:如果您有一个 XPath 并且想要获取一个节点,那么您需要做的是准备一个包含数据的 XMLDocument。您可以使用上面的代码来遍历数据以提供帮助您构建一个XMLDocument,然后使用您的 XPath 查询该文档。

    【讨论】:

      【解决方案2】:

      这是处理所有数据的基本代码:

      static void IterateDictionary(Dictionary<string, object> dictionary)
          {
              foreach (var pair in dictionary)
              {
                  System.Console.WriteLine("Processing key: " + pair.Key);
                  object value = pair.Value;
                  var subDictionary = value as Dictionary<string, object>;
                  if (subDictionary != null)
                  {
                      // recursive call to process embedded dictionary
                      // warning: stackoverflowexception might occur for insanely embedded data: dictionary in dictionary in dictionary in . etc
                      IterateDictionary(subDictionary);
                  }
                  else
                  {
                      // process data
                      System.Console.WriteLine("data: {0}", value);
                  }
              }
          }
      

      希望对你有帮助

      【讨论】:

        【解决方案3】:

        我建议使用 Json.NET 来序列化您的对象,但是,您提到输入是动态的,但属性是否标准化?查看您的示例,有几个重复的字段。您可以通过执行将 json 反序列化到您的类中

        JsonConvert.DeserializeObject<YOUR_CUSTOM_OBJECT>
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-11-23
          • 2012-07-07
          • 2023-03-14
          • 2020-05-16
          • 2012-07-04
          • 2019-11-29
          相关资源
          最近更新 更多