使用webclient从Web服务获取json而不用其他方法操作数据

时间:2013-03-11 13:40:01

标签: c# json web-services windows-phone-8 webclient

我正在开发Windows Phone 8,我想知道当我们调用WebClient的DownloadStringCompleted时是否可以用相同的方法操作数据?

private void DownloadDataFromWebService(String uri)
    {
        WebClient wc = new WebClient();
        wc.DownloadStringAsync(new Uri(uri));
        wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
    }

    private void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
    {
        RootObject r = JsonConvert.DeserializeObject<RootObject>(e.Result);
        List<Category> listeCategories = r.Result;
    }

因此,我想只在一个方法中管理所有代码,因为我想返回一个对象 例如,

private List<Category> GetCategories(String uri)
    {
        WebClient wc = new WebClient();
        wc.DownloadStringAsync(new Uri(uri));
        .....
        .....
        RootObject r = JsonConvert.DeserializeObject<RootObject>(e.Result);
        return (List<Category>) r.Result;
    }

1 个答案:

答案 0 :(得分:1)

是的,由于神奇的TaskCompletionSource类http://msdn.microsoft.com/en-us/library/dd449174(v=vs.95).aspx,这是可能的。下载:

async Task<List<object>> getCategories(String uri)
{
    var taskCompletionObj = new TaskCompletionSource<string>();
    var wc= new webClient();
    wc.DownloadStringAsync(new URI(uri, Urikind.Absolute)) += (o, e) =>
    {
    taskCompletionObj.TrySetResult(e.Result);
    };
    string rawString = await taskCompletionObj.Task;
    RootObject r = JsonConvert.DeserializeObject<RootObject>(rawString);
    return (List<Category>)r.Result; 
}

使用:var x = await getCategories(myURI);