簡體   English   中英

使用C#訪問JSON中的多個數組

[英]Accessing multiple arrays in JSON using C#

我的JSON看起來像這樣:

    {"2013" : [
        { "date":"2013-01-09 12:00:00","height":0 },
        { "date":"2013-01-19 12:00:00","height":3 },
        { "date":"2013-01-29 12:00:00","height":2 }],
    "2012" : [
        { "date":"2012-02-09 12:00:00","height":0 },
        { "date":"2012-02-19 12:00:00","height":4 },
        { "date":"2012-02-29 12:00:00","height":2 }],
    "2011" : [
        { "date":"2011-03-09 12:00:00","height":3 },
        { "date":"2011-03-19 12:00:00","height":8 },
        { "date":"2011-03-29 12:00:00","height":2 }]
   }

我想做的是獲取所有日期和高度,但是我每年只能使用以下代碼來做到這一點:

    public class Report
    {
        public DateTime Date { get; set; }
        public int Height { get; set; }
    }

    JObject data = JObject.Parse(sr);
    var postTitles = from p in data["2013"]
                     select new Report
                     {
                         Date = DateTime.Parse((string)p["date"]),
                         Height = (int)p["height"]
                     };

我當時在考慮使用for循環,但嘗試在data [“”]內部進行變量操作將不起作用。 我也正在考慮執行var postTitles + =語句,但也不允許這樣做。 關於我應該如何處理的任何想法? 我正在使用JSON.NET,建議我每年做一堂課(即2013、2012、2011),但我希望它們在一個課下,以便於操作數據。

我對您使用的LINQ語法不是很好,但是您想要做的就是從許多列表中創建一個列表。 因此,您想使用LINQ的SelectMany映射操作。

var postTitles = data.Children()
        .SelectMany(subitems => subitems.First)
        .Select(dataOfYear =>
            new Report
                {
                    Date = DateTime.Parse((string)dataOfYear ["date"]),
                    Height = (int)dataOfYear ["height"]
                }
            );

如果您只需要每年的前100個報告,則可以這樣做:

var postTitles = data.Children()
        .SelectMany(subitems => subitems.First)
        .Take(100)
        .Select(dataOfYear =>
            new Report
                {
                    Date = DateTime.Parse((string)dataOfYear ["date"]),
                    Height = (int)dataOfYear ["height"]
                }
            );

或者,如果您只想釋放UI線程,則可以在后台線程中運行它:

var postTitles = await Task.Run(() => data.Children()
        .SelectMany(subitems => subitems.First)
        .Select(dataOfYear =>
            new Report
                {
                    Date = DateTime.Parse((string)dataOfYear ["date"]),
                    Height = (int)dataOfYear ["height"]
                }
            ));

我轉過頭來扭了一下馬克的煩惱,然后想到了:

var postTitles = data.Children() // Select array container properties, like "2013"
        .SelectMany(x => x.First) // Select each subitem from every array
        .Select(r => // Create a report for each item
            new Report
                {
                    Date = DateTime.Parse((string)r["date"]),
                    Height = (int)r["height"]
                }
            );

希望內聯注釋能夠充分解釋邏輯。

暫無
暫無

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

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