我正在学习如何进行 API 调用并在我的响应中不断遇到问题(反序列化 JSON)。
我针对同一问题检查了多种解决方案,但没有成功。
我的设置方式有什么问题吗?
注意:我想使用 Twitter API(因此是 Tweets 和 Tweet 类),但我正在对简单的虚拟数据测试我的 Get 请求。
public class HomeController : Controller
{
Tweets model = null;
public ActionResult Index()
{
var client = new HttpClient();
client.Timeout = TimeSpan.FromMinutes(30);
var task =
client.GetAsync(
"http://jsonplaceholder.typicode.com/posts/")
.ContinueWith((taskwithresponse) =>
{
var response = taskwithresponse.Result;
var readtask = response.Content.ReadAsAsync<Tweets>();
readtask.Wait();
model = readtask.Result;
});
task.Wait();
return View(model.results);
}
}
public class Tweets
{
public Tweet[] results;
}
public class Tweet
{
[JsonProperty("body")]
public string UserName { get; set; }
[JsonProperty("title")]
public string TweetText { get; set; }
}
使用
List<Tweet>
作为模型。
public ActionResult Index2()
{
List<Tweet> model = null;
var client = new HttpClient();
client.Timeout = TimeSpan.FromMinutes(30);
var task =
client.GetAsync(
"http://jsonplaceholder.typicode.com/posts/")
.ContinueWith((taskwithresponse) =>
{
var response = taskwithresponse.Result;
var readtask = response.Content.ReadAsAsync<List<Tweet>>();
readtask.Wait();
model = readtask.Result;
});
task.Wait();
return View(model);
}