2017-02-28 125 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"));