首页 > 解决方案 > 使用 asp.net mvc 使用 stackexchange Api

问题描述

我想在我的 ASP.Net 应用程序中使用 StackExchange API。

我制作了模型、控制器和视图,但它不起作用。它不断给我以下错误:

无法将当前 JSON 对象(例如 {"name":"value"})反序列化为类型“System.Collections.Generic.List`1[TaskTrial2.Models.question]”,因为该类型需要 JSON 数组(例如 [1, 2,3]) 正确反序列化。

模型

public class question
{
    public List<string> tags { get; set; }
    public string link { get; set; }
    public owner owner { get; set; }
    public bool is_answered { get; set; }
    public long view_count { get; set; }
    public string last_activity_date { get; set; }
    public long score { get; set; }
    public long answer_count { get; set; }
    public string creation_date { get; set; }
    public string question_id { get; set; }
    public string title { get; set; }




}
public class owner {
    public string user_id { get; set; }
    public string reputation { get; set; }
    public string user_type  { get; set; }
    public string profile_image { get; set; }
    public string display_name { get; set; }
    public string link { get; set; }

}

控制器

    public ActionResult Index()
    {

        List<question> questions = null;

        HttpClientHandler handler = new HttpClientHandler();
        handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
        using (var Client = new HttpClient(handler))
        {
            Client.BaseAddress = new Uri("https://api.stackexchange.com/");
            //HTTP GET
            Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/jason"));
            var response = Client.GetAsync("2.2/questions?site=stackoverflow");
            response.Wait();
            var result = response.Result;

            if (result.IsSuccessStatusCode)
            {
                var readTask = result.Content.ReadAsAsync<List<question>>();
                readTask.Wait();
                questions = readTask.Result;


            }

        }

        return View(questions);
    }

看法

@model IEnumerable<TaskTrial2.Models.question>
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
   }


<table cellpadding="2" cellspacing="2" border="0">
<tr>

    <th>link</th>

</tr>

@foreach (var item in Model)
{

    <tr>
        <td>
            @item.link
        </td>

    </tr>

}

标签: c#asp.netasp.net-web-api

解决方案


当您的请求首先收到问题的包装时,您正在尝试直接序列化为问题列表

public class StackResponseWrapper
{
    public List<Question> items { get; set;}
    public bool has_more {get; set; }
    public int quota_max { get; set; }
    public int quota_remaining { get; set; }
}

我没有研究响应的结构,但我猜这是一个分页包装器,可以通用,例如(StackResponseWrapper<Question>),但我会让你调查。

反序列化 json 时的关键是确保结构与您尝试反序列化的结构相匹配


推荐阅读