1

I have a piece of code, which should grab info from a URL. Get the value called lowest_price and then parse it into a variable, but there is a $ sign in the JSON so I had to remove it and after that I can't Parse the JSON correctly.

My code:

var tokenPrice = JObject.Parse(steamMarket).ToString().Replace("$", " ");
double marketPrice = tokenPrice["lowest_price"];

JSON

{"success":true,"lowest_price":"$5.61","volume":"6","median_price":"$5.61"}

Error:

Argument 1: cannot convert from 'string' to 'int'

  • Possible duplicate of [Problem parsing currency text to decimal type](http://stackoverflow.com/questions/4953037/problem-parsing-currency-text-to-decimal-type) – Cameron Feb 28 '17 at 15:22

3 Answers3

3
double marketPrice = double.Parse(JObject.Parse(steamMarket)["lowest_price"].ToString().Replace("$", ""));
Ðаn
  • 10,934
  • 11
  • 59
  • 95
Chris
  • 679
  • 1
  • 11
  • 26
0

tokenPrice["lowest_price"] is a string and c# will not automatically convert types for you.

var tokenPrice = JObject.Parse(steamMarket);
double marketPrice = double.Parse(tokenPrice["lowest_price"].ToString().Replace("$", ""));
Tim
  • 606
  • 4
  • 7
  • That gives tokenPrice the value of Replace which is a string. You cannot index into a string using a string. It has the same problem as the original code. – Palle Due Feb 28 '17 at 15:39
0

You can also do:

string json = "{\"success\":true,\"lowest_price\":\"$5.61\",\"volume\":\"6\",\"median_price\":\"$5.61\"}";
var jObject = Newtonsoft.Json.Linq.JObject.Parse(json);
double tokenPrice = double.Parse((string )jObject["lowest_price"], NumberStyles.Currency, new CultureInfo("en-US"));
Palle Due
  • 5,929
  • 4
  • 17
  • 32