2013-05-16 57 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); 
      } 
     } 
    } 

希望這有助於