Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

So here is my problem, I am using CoinMarketCap’s api to get cryptocurrency information for my app. The problem is that I am not able to read the properties from the JSON. I am trying to get the current crypto price. I feel like I’m close, I managed to cast the whole thing to JSON and access the first nested data, however afterwards it’s not a JObject anymore, but a JArray, so I can’t simply access properties by name I believe.

Here is the actual code:

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);
    }

The error I get when I get the line "var cryptoCurrency = (JObject)data[coinSymbol];" is the following one:
System.InvalidCastException: ‘Unable to cast object of type ‘Newtonsoft.Json.Linq.JArray’ to type ‘Newtonsoft.Json.Linq.JObject’.’

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Lets say the parameter "coinSymbol" for the example is equal to "BTC", this would be the JSON I get:

    {{
  "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"
          }
        }
      }
    ]
  }
}}

Here is everything I tried to be able to read properties of a nested JSON in C#:

  1. Retrieving value from a JSON string
  2. Reading and Writing Nested data JSON in C#
  3. Deserialize Nested JSON
  4. Unable to cast object of type 'Newtonsoft.Json.Linq.JObject' to type 'Newtonsoft.Json.Linq.JArray'
  5. Retrieve required string from bigger JSON string
  6. https://github.com/lzehrung/coinmarketcap/tree/master
  7. https://code-maze.com/csharp-get-value-by-key-from-jobject/
  8. How to get a JSON string from URL?
  9. And more that I lost

>Solution :

That JSON value is an array, but you’re casting it as if it’s not.

Try this to get the first element of the array:

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading