gpt4 book ai didi

c# - 使用 asp.net mvc 使用 stackexchange Api

转载 作者:太空宇宙 更新时间:2023-11-03 14:45:38 25 4
gpt4 key购买 nike

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

我制作了模型、 Controller 和 View ,但它们无法正常工作。它一直给我以下错误:

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[TaskTrial2.Models.question]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.

型号

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; }

}

Controller

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

关于c# - 使用 asp.net mvc 使用 stackexchange Api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54328880/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com