我在使用 C#(VS 2017,.Net 4.6)代码时遇到了一些麻烦。如果有人能帮忙就好了。我有一个 JSON 文件:
{
"makerCommission": 10,
"takerCommission": 10,
"buyerCommission": 0,
"updateTime": 1540015045989,
"balances": [
{
"asset": "BTC",
"free": "0.22222222",
"locked": "0.00000000"
},
{
"asset": "LTC",
"free": "2.00000000",
"locked": "3.00000000"
},
{
"asset": "ETH",
"free": "4.00000000",
"locked": "5.00000000"
}
]
}
Run Code Online (Sandbox Code Playgroud)
我想使用以下方法检索任何硬币的“免费”价值:
result = (dynamic)JArray.Parse(MyData)
Run Code Online (Sandbox Code Playgroud)
我不想检索所有免费值。如果我选择 BTC,我怎样才能得到 0.22222222?
首先,你的整体 JSON 不代表一个数组,它代表一个包含数组的对象。所以你需要使用JObject.Parse而不是JArray.Parse.
您可以使用以下LINQ-to-JSON代码asset在数组中查找特定free值,然后从中获取值:
JObject obj = JObject.Parse(json); // Parse the JSON to a JObject
string free = obj["balances"] // Navigate down to the "balances" array
.Where(jt => (string)jt["asset"] == "BTC") // Find the object(s) containing the asset you want
.Select(jt => (string)jt["free"]) // From those get the "free" value
.FirstOrDefault(); // Take the first of those
Run Code Online (Sandbox Code Playgroud)
小提琴:https : //dotnetfiddle.net/uFjSib
| 归档时间: |
|
| 查看次数: |
8452 次 |
| 最近记录: |