簡體   English   中英

C#解析JSON數組元素

[英]C# Parse JSON Array Elements

我正在VS 2012中使用Windows 8 Store應用程序,並且是C#和XAML的新功能。 使用JsonArray解析Json feed,如何從另一個數組中的數組中獲取元素?

[

    {
        "item_id": 2270978,
        "item_title": "This is the title",
        "roles": [

            {
                "item_url": "http://www.blahblah.com/161089",
                "parent_url": "http://www.blahblah.com",
            },
            {
                "item_url": "http://www.blahblah.com/469888",
                "parent_url": "http://www.blahblah.com",
            }

        ],
    }
]

我以為另一個foreach可以在原始的foreach中使用,但出現錯誤:

無法將[]的索引應用於類型為'Windows.Data.Json.IJsonValue'的表達式

           foreach (var item in items)
            {
                JsonObject theItem = item.GetObject();
                FeedItem feedItem = new FeedItem();

                feedItem.PubDate = System.DateTime.Now;
                feedItem.Title = theItem["item_title"].GetString();
                feedItem.Author = "Me";
                feedItem.ItemId = (int)(theItem["item_id"].GetNumber());
                feedItem.Content = theItem["item_body"].GetString();
                feedItem.Link = new Uri(theItem["permalink_url"].GetString());

                var roles = theItem["roles"].GetArray();
/* TRIED LIKE THIS DOESN'T WORK
                foreach (var role in roles)
                {
                    feedItem.ContentUrl = new Uri(role["item_url"].GetString());
                }
*/
                feed.Items.Add(feedItem);
            }

您正在遍歷錯誤的變量。 應該:

            var roles = theItem["roles"].GetArray();
            foreach (var role in roles)
            {
                feedItem.ContentUrl = new Uri(role.GetObject()["item_url"].GetString());
            }

此外,您輸入的JSON字符串中沒有content_url元素。 它不應該是item_urlparent_url嗎?

暫無
暫無

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

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