当我得到显示响应时,我得到的只是一个空结果。我认为它可能是班级,因为我连接到http。有任何想法吗 ?谢谢 !
public class info
{
public class Text
{
public int userId { get; set; }
public int id { get; set; }
public string title { get; set; }
public string body { get; set; }
}
这是电话:
Device.BeginInvokeOnMainThread(async () =>
{
RestClient client = new RestClient();
var apiresult = await client.Get<info>("https://jsonplaceholder.typicode.com/posts");
if (apiresult != null)
{
labelchange.Text = apiresult.Text.title;
}
});
和实际的REST
public class RestClient
{
public async Task <T> Get <T>(string url)
{
try
{
HttpClient client = new HttpClient();
var response = await client.GetAsync(url);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
var jsonstring = await response.Content.ReadAsStringAsync();
return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(jsonstring);
}
}
catch
{
}
return default(T);
}
}
传递给RestClient的对象类型不正确。从https://jsonplaceholder.typicode.com/posts返回的类型是List<Text>
因此,您应该更改以下行:
var apiresult = await client.Get<List<Text>>("https://jsonplaceholder.typicode.com/posts");
要访问结果中的成员,只需foreach循环结果中的项:
foreach (var info in apiresult)
{
// Do something with info. e.g. info.userId, info.id...
}