2009-09-05 25 views
3

我想在我的C#控制檯應用程序中使用Goolge AJAX Feed API將返回提要保存爲C#集合,以便我可以在.net應用程序中使用此.net collcetion。如何從C#代碼讀取Google AJAX Feed API結果?

我注意到谷歌給了一個Java訪問代碼片段,但我不知道如何在C#中編碼它。 我知道有一個非常好的.net開源庫Json.NET我們可以用它來讀寫JSON格式的數據。

有人可以給我一個exmpale如何使用C#和Json.NET玩Google AJAX Feed API嗎?

最終解決方案:

public class FeedApiResult 
{ 
    public ResponseData responseData { get; set; } 
    public string responseDetails { get; set; } 
    public string responseStatus { get; set; } 
} 

public class ResponseData 
{ 
    public Feed feed { get; set; } 
} 

public class Feed 
{ 
    public string title { get; set; } 
    public string link { get; set; } 
    public string author { get; set; } 
    public string description { get; set; } 
    public string type { get; set; } 
    public List<Entry> entries { get; set; } 
} 

public class Entry 
{ 
    public string title { get; set; } 
    public string link { get; set; } 
    public string author { get; set; } 
    public string publishedDate { get; set; } 
    public string contentSnippet { get; set; } 
    public string content { get; set; } 

} 

var url = "http://ajax.googleapis.com/ajax/services/feed/load?q=http%3A%2F%2Fwww.digg.com%2Frss%2Findex.xml&v=1.0"; 
var wc = new WebClient(); 
var rawFeedData = wc.DownloadString(url); 

//You can use System.Web.Script.Serialization if you don't want to use Json.NET 
JavaScriptSerializer ser = new JavaScriptSerializer(); 
FeedApiResult foo = ser.Deserialize<FeedApiResult>(rawFeedData); 

//Json.NET also return you the same strong typed object  
var apiResult = JsonConvert.DeserializeObject<FeedApiResult>(rawFeedData); 

回答

4

我只是看着例子,這裏是我怎麼會去了解它。

  1. 構建提要URL(閱讀文檔)
  2. 使用WebClientDownload the URL as a String
  3. 使用Json.NET來讀取字符串。
  4. 使用一個for循環來讀取每個條目

例如,一個快速的未經檢驗的黑客:

// 1. 
var url = "'http://ajax.googleapis.com/ajax/services/feed/load?q=http%3A%2F%2Fwww.digg.com%2Frss%2Findex.xml&v=1.0"; 

// 2. 
var wc = new WebClient(); 
var rawFeedData = wc.DownloadString(url); 

// 3. 
var feedContent = JObject.Parse(rawFeedData); 

// ... 
var entries = feedContent["entries"]; 

for (int i = 0; i < entries.Length; i++) { 
    var entry = entries[i]; 

    // insert entry into your desired collection 
} 

但是,如果你想強類型的類,你必須首先做一個類「看起來像」,也就是從進料API首先返回的數據,即

public class FeedApiResult { 
    public FeedApiFeedObj responseData { get; set; } 
    // snip ... 
} 

public class FeedApiFeedObj { 
    public string title { get; set; } 
    public string link { get; set; } 
    // snip ... 
} 

然後在步驟#3,你可以使用這樣的方法反序列化:

var apiResult = JsonConvert.DeserializeObject<FeedApiResult>(feedContent) 

...

希望這有助於!

+0

謝謝Chakrit,我會很快測試你的代碼。 – CodeYun 2009-09-05 03:06:32