gpt4 book ai didi

c# - 如何从 JArray 中选择元素的值

转载 作者:行者123 更新时间:2023-12-05 00:48:10 25 4
gpt4 key购买 nike

我在使用 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"
}
]
}

我想使用以下方法检索任何硬币的“免费”值(value):

result = (dynamic)JArray.Parse(MyData)

我不想检索所有自由值。如果我选择 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

fiddle :https://dotnetfiddle.net/uFjSib

关于c# - 如何从 JArray 中选择元素的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52907413/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com