我正在开发一个新的Windows Phone 8应用程序。我正在连接到返回有效json数据的Web服务。我正在使用longlistselector来显示数据。当我在GetAccountList()中使用字符串json时,此方法工作正常;但是从DataServices类接收数据时,出现错误“无法将类型'System.Threading.Tasks.Task'隐式转换为字符串”。不知道出了什么问题。欢迎任何帮助。谢谢!
DataServices.cs
public async static Task<string> GetRequest(string url)
{
HttpClient httpClient = new HttpClient();
await Task.Delay(250);
HttpResponseMessage response = await httpClient.GetAsync(url);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Debug.WriteLine(responseBody);
return await Task.Run(() => responseBody);
}
AccountViewModel.cs
public static List<AccountModel> GetAccountList()
{
string json = DataService.GetRequest(url);
//string json = @"{'accounts': [{'id': 1,'created': '2013-10-03T16:17:13+0200','name': 'account1 - test'},{'id': 2,'created': '2013-10-03T16:18:08+0200','name': 'account2'},{'id': 3,'created': '2013-10-04T13:23:23+0200','name': 'account3'}]}";
List<AccountModel> accountList = new List<AccountModel>();
var deserialized = JsonConvert.DeserializeObject<IDictionary<string, JArray>>(json);
JArray recordList = deserialized["accounts"];
foreach (JObject record in recordList)
{
accountList.Add(new AccountModel(record["name"].ToString(), record["id"].ToString()));
}
return accountList;
}
更新:我稍作更改,现在就像一个魅力。谢谢你的帮助!DataServices.cs
//GET REQUEST
public async static Task<string> GetAsync(string url)
{
var httpClient = new HttpClient();
var response = await httpClient.GetAsync(url);
string content = await response.Content.ReadAsStringAsync();
return content;
}
AccountViewModel.cs
public async void LoadData()
{
this.Json = await DataService.GetAsync(url);
this.Accounts = GetAccounts(Json);
this.AccountList = GetAccountList(Accounts);
this.IsDataLoaded = true;
}
public static IList<AccountModel> GetAccounts(string json)
{
dynamic context = JObject.Parse(json);
JArray deserialized = (JArray)JsonConvert.DeserializeObject(context.results.ToString());
IList<AccountModel> accounts = deserialized.ToObject<IList<AccountModel>>();
return accounts;
}
public static List<AlphaKeyGroup<AccountModel>> GetAccountList(IList<AccountModel> Accounts)
{
List<AlphaKeyGroup<AccountModel>> accountList = AlphaKeyGroup<AccountModel>.CreateGroups(Accounts,
System.Threading.Thread.CurrentThread.CurrentUICulture,
(AccountModel s) => { return s.Name; }, true);
return accountList;
}
那行是你的问题:
return await Task.Run(() => responseBody);
你尝试过吗?:
return responseBody;
也尝试一下:
public async static List<AccountModel> GetAccountList()
{
string json = await DataService.GetRequest(url);
...
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句