2013-05-16 60 views
0

我有一个json对象,它已被转换为字典列表。将JSON如下:如何遍历C#中的通用字典列表#

{ 
"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格式可以根据用户输入而变化。

enter image description here

回答

3

假设实际值(如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查询文档。

0

我会建议使用Json.NET序列化你的对象,但是,你所提到的输入是动态的,但属性标准化?看看你的样品,有几个重复的领域。您可以通过执行

JsonConvert.DeserializeObject<YOUR_CUSTOM_OBJECT> 
1

反序列化JSON到您的类下面是处理所有数据的基本代码:

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); 
      } 
     } 
    } 

希望这有助于