【发布时间】:2021-02-25 11:21:13
【问题描述】:
有没有一种好方法可以从最后一个到第一个遍历反序列化的 JSON 对象?即,以下代码我可以从第一个到最后一个迭代并记录“n”个值,直到它满足我的计数条件以进行进一步处理:
protected void testButton_Click(object sender, EventArgs e)
{
List<decimal> priceHistory = new List<decimal>();
var client = new RestClient("https://api.tdameritrade.com/v1/marketdata/" + inputSymbol + "/pricehistory?periodType=year&period=1&frequencyType=daily&frequency=1&needExtendedHoursData=false");
client.Timeout = -1;
var request = new RestRequest(Method.GET);
request.AddHeader("Authorization", "Bearer " + ReadAccessToken());
request.AddParameter("text/plain", "", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
dynamic history = JsonConvert.DeserializeObject<JObject>(response.Content);
int count = 0;
foreach (var child in history["candles"])
{
count += 1;
while (count <= 100)
{
decimal close = child["close"];
priceHistory.Add(close);
break;
}
}
decimal simpleMovingAverage = priceHistory.Average();
responseLabel.Text = simpleMovingAverage.ToString();
//output is taking the first 100 close prices returned from the JSON response and averaging those values.
}
但是,我找不到解决方案是如何从最后一个嵌套的 JSON 对象开始并从后到前的样式添加值。我试图将聚合从计算第一个嵌套对象 + 'n' 下一个值顺序到列表中的前一个值,到实际取响应中的最后一个嵌套 JSON 对象并将其与之前的每个 'n' 值取平均值,直到计数条件已经满足。
编辑
带有任意 'n' 句点的 JSON 示例供参考:
{
"candles": [
{
"open": 172.51,
"high": 176.36,
"low": 171.5,
"close": 171.86,
"volume": 2292877,
"datetime": 1582524000000
},
{
"open": 172.18,
"high": 172.945,
"low": 165.8,
"close": 166.65,
"volume": 2358560,
"datetime": 1582610400000
},
{
"open": 168.28,
"high": 169.38,
"low": 165.61,
"close": 166.92,
"volume": 2545782,
"datetime": 1582696800000
},
{
"open": 164.4,
"high": 166.55,
"low": 159.96,
"close": 159.99,
"volume": 2957507,
"datetime": 1582783200000
},
{
"open": 155.29,
"high": 158.92,
"low": 152.66,
"close": 156.48,
"volume": 3053876,
"datetime": 1582869600000
},
{
"open": 157.92,
"high": 164.0,
"low": 156.55,
"close": 163.92,
"volume": 2532128,
"datetime": 1583128800000
}
],
"symbol": "DE",
"empty": false
}
【问题讨论】: