无法将当前 JSON 数组(例如 [1,2,3])反序列化为类型......我做错了什么?

问题描述 投票:0回答:1

我正在学习如何进行 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; }
}
c# json rest dotnet-httpclient
1个回答
2
投票

使用

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);
}
© www.soinside.com 2019 - 2024. All rights reserved.