2017-02-28 59 views
1

我有一段代码,它应该从URL中获取信息。获取名为lowest_price的值,然后将其解析为一个变量,但JSON中有一个$符号,因此我必须将其删除,之后我无法正确解析JSON。C#|从URL抓取JSON不能将字符串转换为int

我的代码:

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

错误:

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

+0

[解析问题货币文本小数类型(的可能的复制http://stackoverflow.com/questions/4953037/problem-parsing-currency-text - 十进制类型) – Cameron

回答

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

tokenPrice [ “LOWEST_PRICE起”]是一个字符串和C#也不会自动进行类型转换为你。

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

这给tokenPrice的值是Replace,它是一个字符串。您不能使用字符串索引到一个字符串。它具有与原始代码相同的问题。 –

+0

你是对的。更新的答案。 – Tim

0

你也可以这样做:

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