使用webclient从webservices获取json,而不需要在其他方法中操作数据
本文关键字:方法 其他 操作 数据 操作数 不需要 webclient webservices 获取 json 使用 | 更新日期: 2023-09-27 18:03:24
我正在开发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;
}
是的,这是可能的,由于神奇的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);