簡體   English   中英

在ASP.NET MVC 5中訪問第二級JSON數組

[英]Accessing second level JSON array in ASP.NET MVC 5

考慮以下JSON對象數組:

JSON:

{
   status: "ok",
   count: 10,
   count_total: 642,
   pages: 65,
 - posts: [
    - {
         id: 681,
         type: "post",
         slug: "lorem_ipsum_dolor_sit_amet",
         url: "/2015/09/lorem_ipsum_dolor_sit_amet/",
         status: "publish",
         title: "Lorem ipsum dolor sit amet",
         title_plain: "Lorem ipsum dolor sit amet",
         content: "Lorem ipsum dolor sit amet",
         excerpt: "Lorem ipsum dolor sit amet",
         date: "2015-09-14 10:06:06",
         modified: "2015-09-22 16:13:55",
       - categories: [
          - {
               id: 23,
               slug: "my_category",
               title: "myCategory",
               description: "",
               parent: 0,
               post_count: 138
            }
         ],
       - attachments: [
          - {
               id: 689,
               url: "http://example.com/wp-content/uploads/example_01.jpg",
               slug: "example_01",
               title: "example_01",
               description: "",
               caption: "",
               parent: 681,
               mime_type: "image/jpeg",
             - images: {
                - full: {
                           url: "/wp-content/uploads/sites/14/2015/09/example_full_01.jpg",
                           width: 952,
                           height: 693
                        }
                       }
           }
         ]
      }
   ]
}

這是我的控制器:

...

public ActionResult News()
{
    ViewBag.News = "";

    try
    {
        dynamic News = new Json("http://www.example.com/api/get_recent_posts/").getJson();
        ViewBag.News = News.@posts;
        ViewBag.total = News.@posts.Count > 3 ? count : News.@posts.Count;
    }
    catch
    {
        Response.Cache.SetExpires(DateTime.Now.AddHours(1));
    }

    return View();
}

...

這是我的看法:

...

@if (ViewBag.News != null)
{
    for (int i = 0; i < ViewBag.total; i++)
    {
        <div class="news">
            <a href="@Html.Raw(ViewBag.News[i].url)"><img src="@Html.Raw(ViewBag.News[i].attachments.images.full.url)" /></a>
            <div class="description">
                <h3><a href="@Html.Raw(ViewBag.News[i].url)">@Html.Raw(ViewBag.News[i].title)</a></h3>
                @Html.Raw(ViewBag.News[i].excerpt)
            </div>
        </div>
    }
}

...

以下三行完美地工作:

@Html.Raw(ViewBag.News[i].url)
@Html.Raw(ViewBag.News[i].title)
@Html.Raw(ViewBag.News[i].excerpt)

我想在“附件”部分中獲取圖片的網址(帖子>附件>圖片>完整>網址),但是以下行不起作用:

@Html.Raw(ViewBag.News[i].attachments.images.full.url)

謝謝。

在您的JSON中, attachments是一個數組。 您需要使用方括號和索引來訪問它。 如果數組中只有1個項目,請嘗試:

@Html.Raw(ViewBag.News[i].attachments[0].images.full.url)

另外,如果您控制JSON(確實如此),請改為將其作為對象。

暫無
暫無

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

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