在ASP中访问二级JSON数组.asp.net MVC 5

本文关键字:数组 JSON asp net MVC 二级 ASP 访问 | 更新日期: 2023-09-27 18:13:56

考虑以下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)

我想在"附件"部分获得图像的URL (posts> attachments> images> full> URL),但以下行不起作用:

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

谢谢。

在ASP中访问二级JSON数组.asp.net MVC 5

在JSON中,attachments是一个数组。你需要用括号和索引来访问它。如果数组中只有一个元素,试试:

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

另外,如果你控制JSON,那就把它变成一个对象。