本文介绍了迭代JObject键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下JObject作为 https://gate.io/api2#trade API.我如何遍历每个都是独立硬币的钥匙,也能得到它的价值.

I have the following JObject as return by https://gate.io/api2#trade API. How do I iterate through each key which is a separate coin also get its value.

我尝试使用Newtonsoft JObject进行解析,如下所示:

I tried to parse it using Newtonsoft JObject Parse like this:

var coinData = JObject.Parse(@"{
    ""result"": ""true"",
    ""available"": {
        ""BTC"": ""0.83337671"",
        ""LTC"": ""94.364"",
        ""ETH"": ""0.07161"",
        ""ETC"": ""82.35029899""
    },
    ""locked"": {
        ""BTC"": ""0.0002"",
        ""YAC"": ""10.01""
    }
}")["available"];

foreach (JToken item in coinData)
{
    item.Key
}

,但随后JToken不能访问键值.我不知道如何进一步解析它.

but then JToken doesn't give access to key values. I don't know how to further parse it.

从gateio api接收到的JSON:

JSON received from gateio api:

{
    "result": "true",
    "available": {
        "BTC": "0.83337671",
        "LTC": "94.364",
        "ETH": "0.07161",
        "ETC": "82.35029899"
    },
    "locked": {
        "BTC": "0.0002",
        "YAC": "10.01"
    }
}

我是否应该在循环中用:"将其中断?如果我将其破坏并替换为引号,则此方法有效.

Should I break it with ':' while iterating in loop? This is working if i break it and replace quotes.

foreach (JToken item in coinData)
{
    var data = item.ToString().Replace("\"", String.Empty).Split(':');
}

var数据有两个部分,1 =>硬币名称,2 =>余额.

var data has two parts, 1 => coin name, 2 => balance.

还有其他合法途径吗?

推荐答案

JToken是所有json令牌类型的基类.在您的情况下,虽然只需要json属性,所以您需要按更窄的类型-JProperty进行过滤.您可以过滤以仅包括如下属性标记:

JToken is base class for all types of json tokens. In your case though you want only json properties, so you need to filter by more narrow type - JProperty. You can filter to include only property tokens like this:

foreach (var item in coinData.OfType<JProperty>()) {
    string coinName = item.Name;
    // to parse as decimal
    decimal balance = item.Value.Value<decimal>();
    // or as string
    string balanceAsString = item.Value.Value<string>();
}

这篇关于迭代JObject键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 16:34