使用 asp.net mvc 使用 stackexchange API



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

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

无法反序列化当前 JSON 对象(例如 {"名称":"值"}) 成类型 '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>
}

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

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 时的关键是确保结构与您尝试反序列化的内容匹配

最新更新