2017-09-04 36 views
0

例JSON數據如何在JSON C#選擇數據的範圍

"Data": [ 
{ 
    "Symbol": "PTT", 
    "CandleCollection": [ 
    { 
     "Open": 248.0, 
     "High": 250.0, //1 

    }, 
    { 
     "Open": 239.0, 
     "High": 241.0, //2 

    }, 
    { 
     "Open": 225.0, 
     "High": 229.0, //3 

    }, 
    { 
     "Open": 215.0, 
     "High": 216.0, //4 

    }, 
    { 
     "Open": 215.0, 
     "High": 218.0, //5 

    }, 

示例:我需要在4

我的JSON輸入代碼來選擇在2個結尾數據的第一數據上C#是:

  foreach (JToken data in jsonInputObj["Data"]) 
      { 
       List<CandleStick> candleArray = new List<CandleStick>(); 

       foreach (JToken candleStick in data["CandleCollection"]) 
       { 
        double open = candleStick["Open"].ToObject<double>(); 
        double high = candleStick["High"].ToObject<double>(); 

        candleArray.Add(new CandleStick(open, high); 
       } 
       CandleCollection candleList = new CandleCollection(candleArray); 
       symbolList.Add(data["Symbol"].ToString(), candleList); 
      } 

//
這個循環是得到以.json文件數據到列表

在這個循環中選擇數據範圍是不可能的?

+0

你能告訴我如何循環?我不擅長代碼編程。 –

+0

上面的循環是否正確讀取所有數據? –

+0

是的。它獲取所有數據。 –

回答

1

只需將最內層的foreach環路替換爲for環路,您就可以輕鬆前往。像:

foreach (JToken data in jsonInputObj["Data"]) 
{ 
     List<CandleStick> candleArray = new List<CandleStick>(); 
     var Candles = data["CandleCollection"]; 
     for (int i = 0; i < Candles.Count(); i++) 
     { 
      //This will skip the first and last 
      if (i == 0 || i == Candles.Count() - 1) continue; 

      JToken candleStick = Candles[i]; 
      double open = candleStick["Open"].ToObject<double>(); 
      double high = candleStick["High"].ToObject<double>(); 

      candleArray.Add(new CandleStick(open, high)); 
     } 

     CandleCollection candleList = new CandleCollection(candleArray); 
     symbolList.Add(data["Symbol"].ToString(), candleList); 
} 

編輯1:

更新我的回答,以適應 - 在您的解決方案爲礦山造成麻煩你。試試這個:

foreach (JToken data in jsonInputObj["Data"]) 
{ 
    List<CandleStick> candleArray = new List<CandleStick>(); 

    int i = 1; 
    int finalCount = data["CandleCollection"].Count(); 
    foreach (JToken candleStick in data["CandleCollection"]) 
    { 
      if (i == 1 || i == finalCount) continue; 
      i += 1; 
      double open = candleStick["Open"].ToObject<double>(); 
      double high = candleStick["High"].ToObject<double>(); 

      candleArray.Add(new CandleStick(open, high)); 
    } 
    CandleCollection candleList = new CandleCollection(candleArray); 
    symbolList.Add(data["Symbol"].ToString(), candleList); 
} 

PS:我相信Count()應該適合你!

+0

據說「'JToken'沒有包含'Length'的定義,並且沒有可以找到接受'JToken'類型的第一個參數的擴展方法'Length'(你是否缺少使用指令或程序集引用?)」 –

+0

嘗試用'Candles.Count()',即'for(int i = 0; i

+0

我試過Count()但是。這是行不通的。 –