我正在使用Json.net,这是我的json:
{
"miner": "t1biSMuXyq5eKkP8zDPViKHF9mbS9ZFLRuF",
"totalHash": 1523943880.832757,
"totalShares": 4089.53223605,
"networkSols": "7644579",
"immature": 0.29784511,
"balance": 0,
"paid": 1092.22974323,
"workers": {
"t1biSMuXyq5eKkP8zDPViKHF9mbS9ZFLRuF": {
"name": "t1biSMuXyq5eKkP8zDPViKHF9mbS9ZFLRuF",
"diff": 54500,
"shares": 106.44625040000004,
"invalidshares": 0,
"currRoundShares": 4082.8793454,
"currRoundTime": 0,
"hashrate": 1523943880.832757,
"hashrateString": "3.05 KSol/s",
"luckDays": "5.574",
"luckHours": "133.768",
"paid": 1092.22974323,
"balance": 0
}
},
"history": {
"t1biSMuXyq5eKkP8zDPViKHF9mbS9ZFLRuF": [
{
"time": 1516522247,
"hashrate": 1600923951.4915187
},
{
"time": 1516526867,
"hashrate": 1523943880.832757
}
]
}
}
我想在内部获取元素hashrateString" workers"在里面" t1biSMuXyq5eKkP8zDPViKHF9mbS9ZFLRuF"但是" t1biSMuXyq5eKkP8zDPViKHF9mbS9ZFLRuF"每次都会改变。
这是我目前的代码:
String dl = webClient.DownloadString("http://hushpool.cloud/api/worker_stats?t1biSMuXyq5eKkP8zDPViKHF9mbS9ZFLRuF");
JObject json = JObject.Parse(dl);
JObject workers = JObject.Parse(JObject.Parse(dl).SelectToken("workers").First.ToString());
label7.Text = (String)json.GetValue("balance");
label8.Text = (String)json.GetValue("pending");
label9.Text = (String)json.GetValue("paid");
label10.Text = (String)workers.GetValue("hashrateString");
我尝试了不同的代码,但没有任何效果。你能帮助我吗?
答案 0 :(得分:1)
由于minerValue
不是常量,因此您需要首先从json获取它并使用它遍历JObject
以获取hashrateString
的值
JObject obj = JObject.Parse(json);
JObject workers = (JObject)obj.GetValue("workers");
string minerValue = obj.GetValue("miner").ToString();
JObject minerWorker = (JObject)workers.GetValue(minerValue);
string hashRate = minerWorker.GetValue("hashrateString").ToString();
更新: 根据您的评论,如果存在属性名称略有不同的场景,您可以使用以下代码来获取对象:
JObject workerMiner = (JObject)workers.Properties().FirstOrDefault(p => p.Name.StartsWith(minerValue)).Value;
请记住,此代码不是生产就绪,因为您需要处理角落/故障情况(例如,json中不存在 worker 或 miner 属性)
答案 1 :(得分:1)
这是使用jsonpath从json文本中检索'hashratestring'
的另一种方法。
JObject obj = JObject.Parse(jsonTxt);
string name = (string)obj.SelectToken("$.workers.*.hashrateString");
Console.WriteLine(name);
输出:
3.05 KSol/s
的工作样本