簡體   English   中英

無法將當前的JSON數組(例如[1,2,3])反序列化為類型……我在做什么錯?

[英]Cannot deserialize the current JSON array (e.g. [1,2,3]) into type… what am I doing wrong?

我正在學習如何進行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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM