2014-01-05 27 views
0

有人可以幫助我弄清楚如何在C#中使用此示例代碼獲取JSON數據中的父數據?反序列化C#中的父JSON數據RootObject

string JSON = JsonConvert.SerializeObject(message["data"]); 
       //Deserialize to strongly typed class i.e., RootObject 
       RootObject obj = JsonConvert.DeserializeObject<RootObject>(JSON); 

       //loop through the list and show on console 
       foreach (Result resultsItem in obj.results) 
       { 
        Console.WriteLine(resultsItem.shipping + "-" + resultsItem.model + "-" + resultsItem.price + 
          "-" + resultsItem.product_name); 

       } 

和根對象類看起來像這樣

public class Result 
{ 
    public string shipping { get; set; } 
    public string model { get; set; } 
    public string price { get; set; } 
    public string item { get; set; } 
    public string product_name { get; set; } 
    public string availability { get; set; } 
} 

public class RootObject 
{ 
    public List<object> cookies { get; set; } 
    public List<Result> results { get; set; } 
    public string connectorGuid { get; set; } 
    public string connectorVersionGuid { get; set; } 
    public string pageUrl { get; set; } 
    public int offset { get; set; } 
} 

我可以編寫代碼來顯示Result類列,但我不知道如何在rootobject類達到「PAGEURL」。我在foreach循環中嘗試了所有可能的名稱,但RootObject中的列只是無法訪問。任何幫助將不勝感激。 謝謝

+0

你在'obj.pageUrl'中得到了什麼?它是空值嗎? –

+0

它不是null。它應該顯示url鏈接。 – Mozung

+0

最後,我想從root對象的表中插入Result和pageURL的所有列。這就是爲什麼我試圖讓所有的foreach循環。 – Mozung

回答

1

這就是你需要的嗎?

foreach (Result resultsItem in obj.results) 
{ 
    Console.WriteLine(resultsItem.shipping 
         + "-" + resultsItem.model 
         + "-" + resultsItem.price 
         + "-" + resultsItem.product_name 
         + "-" + obj.pageUrl); 

} 

此代碼將顯示每行結果的pageUrl

+0

是的,它的工作原理:D – Mozung