如何使用 NewtonSoft 从 C# 中的嵌套 JSON 中读取属性

How to read property from nested JSON in C# using NewtonSoft

提问人:Dolotboy 提问时间:7/13/2023 更新时间:7/13/2023 访问量:94

问:

所以这是我的问题,我正在使用 CoinMarketCap 的 api 来获取我的应用程序的加密货币信息。问题是我无法从 JSON 中读取属性。我正在尝试获取当前的加密货币价格。我觉得我很接近了,我设法将整个事情转换为 JSON 并访问第一个嵌套数据,但是之后它不再是 JObject,而是 JArray,所以我不能简单地按名称访问属性我相信。

下面是实际代码:

public static string GetCryptoUnitValue(string coinSymbol)
    {
        var URL = new UriBuilder("https://pro-api.coinmarketcap.com/v2/cryptocurrency/quotes/latest");

        var queryString = HttpUtility.ParseQueryString(string.Empty);
        queryString["symbol"] = coinSymbol;
        queryString["convert"] = "USD";

        URL.Query = queryString.ToString();

        var client = new WebClient();
        client.Headers.Add("X-CMC_PRO_API_KEY", API_KEY);
        client.Headers.Add("Accepts", "application/json");

        string cryptoData = client.DownloadString(URL.ToString());

        JObject json = JObject.Parse(cryptoData);
        var data = (JObject)json["data"];
        var cryptoCurrency = (JObject)data[coinSymbol];
        var quote = cryptoCurrency["quote"];
        var usd = (JObject)quote["USD"];
        var price = (double)usd["price"];
        MessageBox.Show(Convert.ToString(price));

        return Convert.ToString(price);
    }

当我得到“var cryptoCurrency = (JObject)data[coinSymbol];”行时,我得到的错误如下:System.InvalidCastException:'无法将'Newtonsoft.Json.Linq.JArray'类型的对象转换为'Newtonsoft.Json.Linq.JObject'。

假设示例的参数“coinSymbol”等于“BTC”,这将是我得到的 JSON:

    {{
  "status": {
    "timestamp": "2023-07-12T17:08:49.341Z",
    "error_code": 0,
    "error_message": null,
    "elapsed": 31,
    "credit_count": 1,
    "notice": null
  },
  "data": {
    "BTC": [
      {
        "id": 1,
        "name": "Bitcoin",
        "symbol": "BTC",
        "slug": "bitcoin",
        "num_market_pairs": 10341,
        "date_added": "2010-07-13T00:00:00Z",
        "tags": [
          {
            "slug": "mineable",
            "name": "Mineable",
            "category": "OTHERS"
          }
        ],
        "max_supply": 21000000,
        "circulating_supply": 19427587,
        "total_supply": 19427587,
        "is_active": 1,
        "infinite_supply": false,
        "platform": null,
        "cmc_rank": 1,
        "is_fiat": 0,
        "self_reported_circulating_supply": null,
        "self_reported_market_cap": null,
        "tvl_ratio": null,
        "last_updated": "2023-07-12T17:07:00Z",
        "quote": {
          "USD": {
            "price": 30500.58272538358,
            "volume_24h": 14011375945.039093,
            "volume_change_24h": -10.7739,
            "percent_change_1h": 0.09624256,
            "percent_change_24h": -0.47967662,
            "percent_change_7d": 0.03734603,
            "percent_change_30d": 18.12871397,
            "percent_change_60d": 13.72165636,
            "percent_change_90d": 0.49714266,
            "market_cap": 592552724448.0867,
            "market_cap_dominance": 49.8913,
            "fully_diluted_market_cap": 640512237233.06,
            "tvl": null,
            "last_updated": "2023-07-12T17:07:00Z"
          }
        }
      }
    ]
  }
}}

以下是我尝试在 C# 中读取嵌套 JSON 属性的所有内容:

  1. 从 JSON 字符串中检索值
  2. 在 C 语言中读取和写入嵌套数据 JSON#
  3. 反序列化嵌套 JSON
  4. 无法将类型为“Newtonsoft.Json.Linq.JObject”的对象强制转换为类型“Newtonsoft.Json.Linq.JArray”
  5. 从更大的 JSON 字符串中检索所需的字符串
  6. https://github.com/lzehrung/coinmarketcap/tree/master
  7. https://code-maze.com/csharp-get-value-by-key-from-jobject/
  8. 如何从URL获取JSON字符串?
  9. 还有更多我失去的东西
C# JSON 嵌套 json.net WebClient

评论


答:

1赞 MStodd 7/13/2023 #1

该 JSON 值是一个数组,但您将其强制转换为好像它不是一样。

尝试以下操作以获取数组的第一个元素:

var cryptoCurrency = ((JArray)data[coinSymbol])[0];