简体   繁体   English

ASP.NET MVC - 在 Razor 页面中显示 JSON - foreach 问题

[英]ASP.NET MVC - Displaying JSON in Razor Page - Problem with foreach

I am new to C# and ASP.NET in general, so please if anyone knows how to fix this problem that I am going to show you, I would gladly appreciate it.我一般是 C# 和 ASP.NET 的新手,所以如果有人知道如何解决我将向您展示的这个问题,我将不胜感激。 So, the problem is.. I can not and do not know how to display the JSON in Razor page, or so called View.所以,问题是..我不能也不知道如何在 Razor 页面或所谓的视图中显示 JSON。 I will show you the code and JSON file.我将向您展示代码和 JSON 文件。

Entity - Class model:实体 - 类模型:

// Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse); 
    public class Source
    {
        public string id { get; set; }
        public string name { get; set; }
    }

    public class Article
    {
        public Source source { get; set; }
        public string author { get; set; }
        public string title { get; set; }
        public string description { get; set; }
        public string url { get; set; }
        public string urlToImage { get; set; }
        public DateTime publishedAt { get; set; }
        public string content { get; set; }
    }

    public class FetchedNews
    {
        public string status { get; set; }
        public int totalResults { get; set; }
        public List<Article> articles { get; set; }
    }

JSON File: JSON 文件:

{"status":"ok","totalResults":38,"articles":[{"source":{"id":null,"name":"CNBC"},"author":"The Associated Press","title":"Hong Kong protester given 9-year term in 1st security case - CNBC","description":"A pro-democracy protester was sentenced Friday to nine years in prison in the closely watched first case under Hong Kong's national security law.","url":"https://www.cnbc.com/2021/07/30/pro-democracy-protester-given-9-year-term.html","urlToImage":"https://image.cnbcfm.com/api/v1/image/106917243-1627372873218-gettyimages-1224906144-AFP_1UP4SA.jpeg?v=1627372232","publishedAt":"2021-07-30T07:37:06Z","content":"A pro-democracy protester was sentenced Friday to nine years in prison in the closely watched first case under Hong Kong's national security law as the ruling Communist Party tightens control over th… [+2386 chars]"}

Method to GET the JSON file from newsapi.org:从 newsapi.org 获取 JSON 文件的方法:

 public async Task<IEnumerable<FetchedNews>> FetchNews()
        {
            List<FetchedNews> newsFetched = new List<FetchedNews>();

            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("https://newsapi.org");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                HttpResponseMessage response = await client.GetAsync("/v2/top-headlines?country=us&apiKey=fa9c19da02df465d8f7d6b0654248a24");
                if (response.IsSuccessStatusCode)
                {
                    var jsondata =  response.Content.ReadAsStringAsync().Result;
                    newsFetched = JsonConvert.DeserializeObject<List<FetchedNews>>(jsondata);

                }
                return newsFetched;
            }
        }

Controller控制器

 [HttpGet]
        [Route("news/fetch")]
        public async Task<ActionResult> Fetch()
        {
            var newsFetched = await news.FetchNews();
            return View(newsFetched);
        }

And I get this error at the end最后我得到这个错误

Cannot deserialize the current JSON object (eg {"name":"value"}) into type 'System.Collections.Generic.List`1[Newspage.Data.Models.FetchedNews]' because the type requires a JSON array (eg [1,2,3]) to deserialize correctly.无法将当前 JSON 对象(例如 {"name":"value"})反序列化为类型“System.Collections.Generic.List`1[Newspage.Data.Models.FetchedNews]”,因为该类型需要一个 JSON 数组(例如 [ 1,2,3]) 正确反序列化。

Yes, I know in the error it says that it requires to me to use JSON Array.是的,我知道在错误中它说它需要我使用 JSON 数组。 I also tried to convert JSON Object to JSON Array but failed.我也尝试将 JSON 对象转换为 JSON 数组但失败了。 Here is also the View这里也是视图

@model IEnumerable<Newspage.Data.Models.FetchedNews>

@{
    ViewBag.Title = "Fetch";
}

<h2>Fetch</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.status)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.totalResults)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.status)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.totalResults)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
            @Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
            @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
        </td>
    </tr>
}

</table>

fethnews is one item , not collectiton so fethnews 是一个项目,而不是collectiton 所以

fix the action修复动作

public async Task<ActionResult<FetchedNews>> FetchNews()
.....
if (response.IsSuccessStatusCode)
                {
var jsondata =  response.Content.ReadAsStringAsync().Result;
 newsFetched = JsonConvert.DeserializeObject<FetchedNews>(jsondata);

                }
 return Ok( newsFetched);

and view并查看

@model Newspage.Data.Models.FetchedNews

.....

@foreach (var item in Model.articles) 

Ensure that your JSON string data and JSON object mappers properties are consistent with each other.确保您的 JSON 字符串数据和 JSON 对象映射器属性彼此一致。 Then if your JSON root object is a single object with status, totalResults and articles list property then use below code ie然后,如果您的 JSON 根对象是具有状态、totalResults 和文章列表属性的单个对象,则使用以下代码,即

newsFetched = JsonConvert.DeserializeObject<FetchedNews>(jsondata);

If however, your target JSON string data is array at root and does not contain status and totalResults, but, follows Article class properties then fetch use below code ie但是,如果您的目标 JSON 字符串数据是根数组,并且不包含状态和 totalResults,但是,遵循文章类属性,然后获取使用下面的代码,即

newsFetched = JsonConvert.DeserializeObject<List<Article>>(jsondata);

Your JSON returns a JSON object, not a JSON array.您的 JSON 返回一个 JSON 对象,而不是一个 JSON 数组。 The

@model IEnumerable<Newspage.Data.Models.FetchedNews>

assumes an enumerable (thus an array in the response).假定一个可枚举(因此响应中的数组)。 Change this to将此更改为

@model Newspage.Data.Models.FetchedNews

and it should work fine.它应该可以正常工作。

Within your page, you can loop through the list of articles with在您的页面中,您可以循环浏览文章列表

@foreach(var article in Model.articles)
{
    //Do something
}

在视图中将此转换为此

@model IEnumerable<List<Newspage.Data.Models.FetchedNews>>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM