0

I want to get a specific element from Json. I can get the "closeoutBid" element but I do not know how to get the
"long" element from the part below:

"unitsAvailable": { "default": { "long": "3003003", "short": "3003003" }

I am doing something wrong here. Any help please? Thank you. I have this code:

 var JsonResP = JsonConvert.DeserializeObject<dynamic>(resultPrice);//Deserialize Json 
 double bidprice = Convert.ToDouble(JsonResP.prices[0].closeoutBid);
 double unitsavailabletoBuy = Convert.ToDouble(JsonResP.prices[0].unitsAvailable.default.long); //Error!!!

And this Json format:

{
  "time": "2021-03-29T18:12:57.651762093Z",
  "prices": [
    {
      "type": "PRICE",
      "time": "2021-03-29T18:12:57.552372868Z",
      "bids": [
        {
          "price": "1.17718",
          "liquidity": 1000000
        },
        {
          "price": "1.17717",
          "liquidity": 2000000
        },
        {
          "price": "1.17716",
          "liquidity": 2000000
        },
        {
          "price": "1.17714",
          "liquidity": 5000000
        }
      ],
      "asks": [
        {
          "price": "1.17724",
          "liquidity": 1000000
        },
        {
          "price": "1.17726",
          "liquidity": 2000000
        },
        {
          "price": "1.17727",
          "liquidity": 2000000
        },
        {
          "price": "1.17728",
          "liquidity": 5000000
        }
      ],
      "closeoutBid": "1.17714",
      "closeoutAsk": "1.17728",
      "status": "tradeable",
      "tradeable": true,
      "unitsAvailable": {
        "default": {
          "long": "3003003",
          "short": "3003003"
        },
        "openOnly": {
          "long": "3003003",
          "short": "3003003"
        },
        "reduceFirst": {
          "long": "3003003",
          "short": "3003003"
        },
        "reduceOnly": {
          "long": "0",
          "short": "0"
        }
      },
      "quoteHomeConversionFactors": {
        "positiveUnits": "0.84942282",
        "negativeUnits": "0.84950941"
      },
      "instrument": "EUR_USD"
    }
  ]
}

I

Paul Phoenix
  • 1
  • 1
  • 2
  • 1
    Why not create classes that represent this json? Then you could deserialize and get anything you need, don't make it hard. I say this because typically user's say they only need this *one thing*, but that tends to get thrown out sooner than later. There are a handful of online converters that will take this `json` and create the needed classes for you. – Trevor Mar 29 '21 at 18:54
  • This is why `dynamic` can be a bad idea -- you never know what you are getting. `JsonResP.prices[0].unitsAvailable.default.long` is actually of type `JValue` so `Convert.ToDouble()` may not know how to deal with it. Better to explicitly deserialize to `JToken` and use the indexers. Or design a data model -- that works well also. – dbc Mar 29 '21 at 20:09

0 Answers0