技术开发 频道

Windows phone如何实现json接口的调用

  实现热门话题数据获取服务

  知道了怎么解析数据后,我们现在将上面所有的实现封装在方法中。

  在GetTrends方法中,使用了一些委托作为参数,以便我们的类可以异步工作。

  l Action> onGetTrendsCompleted, 在热门主题数据准备处理时调用。

  l Action onError, 在获取热门主题信息发生错误时调用。

  l Action onFinally, 总是被调用, 无论是否有错误发生.

  因此方法的签名如下:

public static void GetTrends(Action<IEnumerable<Trend>>
    onGetTrendsCompleted
= null, Action<Exception> onError = null,
    Action onFinally
= null)

  接下来我们需要WebClient来请求服务器端,以获取json数据。

WebClient webClient = new WebClient();

// register on download complete event
webClient.OpenReadCompleted
+= delegate(object sender, OpenReadCompletedEventArgs e)
{
    ...
};

webClient.OpenReadAsync(
new Uri(string.Format
    (WhatTheTrendSearchQuery, WhatTheTrendApplicationKey)));

  这里的WhatTheTrendSearchQuery的定义如下:

  private const string WhatTheTrendSearchQuery =

  "http://api.whatthetrend.com/api/v2/trends.json?api_key={0}";

  onGetTrendsCompleted, onError, onFinally的事件处理代码如下:

/// <summary>
/// Gets the trends.
/// </summary>
/// <param name="onGetTrendsCompleted">The on get trends completed.</param>
/// <param name="onError">The on error.</param>
public static void GetTrends(Action<IEnumerable<Trend>>
    onGetTrendsCompleted
= null, Action<Exception> onError = null,
    Action onFinally
= null)
{
    WebClient webClient
= new WebClient();

    
// register on download complete event
    webClient.OpenReadCompleted
+=
    delegate(
object sender, OpenReadCompletedEventArgs e)
    {
        try
        {
            
// report error
            
if (e.Error != null)
            {
                
if (onError != null)
                {
                    onError(e.Error);
                }
                return;
            }

            
// convert json result to model
            Stream stream
= e.Result;
            DataContractJsonSerializer dataContractJsonSerializer
=
        
new DataContractJsonSerializer(typeof(TrendsResults));
            TrendsResults trendsResults
=
        (TrendsResults)dataContractJsonSerializer.ReadObject(stream);

            
// notify completed callback
            
if (onGetTrendsCompleted != null)
            {
                onGetTrendsCompleted(trendsResults.trends);
            }
        }
        finally
        {
            
// notify finally callback
            
if (onFinally != null)
            {
                onFinally();
            }
        }
    };

    webClient.OpenReadAsync(
new Uri(string.Format
    (WhatTheTrendSearchQuery, WhatTheTrendApplicationKey)));
}

  使用热门话题服务

  最后为了在页面上显示10大热门信息,我们可以在MainPage.xmal.cs中放入如下的代码,以便实现数据和列表控件的绑定。

private void Button_Click(object sender, RoutedEventArgs e)
        {
            TwitterService.GetTrends(
               (items)
=> { listbox.ItemsSource = items; },
               (exception)
=> { MessageBox.Show(exception.Message); },
              
null
               );
        }
0
相关文章