反序列化Json字符串不工作


Deserialize Json String not working

我想从php网站反序列化Json字符串。不幸的是,每次我尝试它,它将返回null为medianPrice....为什么?

public class PriceInfo
{
    public string success { get; set; }
    public double lowestPrice { get; set; }
    public string volume { get; set; }
    public string medianPrice { get; set; }
}
WebClient client = new WebClient();
string url = "http://steamcommunity.com/market/priceoverview/?country=US&currency=1&appid=730&market_hash_name=" + name;
byte[] html = client.DownloadData(url);
UTF8Encoding utf = new UTF8Encoding();
string return_value = utf.GetString(html);
PriceInfo priceInfo = new JavaScriptSerializer().Deserialize<PriceInfo>(return_value);
if( Double.Parse(priceInfo.medianPrice) > 0.15 )
{
      string blablu = "hello";
}

从网站返回的Json如下:

{"success":true,"lowest_price":"&#36;0.04","volume":"3,952","median_price":"&#36;0.02"}

我希望你能帮助我!

我强烈建议您尝试使用Newtonsoft。Json

你会发现处理Jason对象更容易

你的代码将是这样的(未测试)

PriceInfo defaultCallResult = JsonConvert.DeserializeObject<PriceInfo>(return_value);

您的JSON属性名为"median_price"(带下划线),但您的c#属性为"medianPrice"。

你可以使用Json。. NET允许您使用属性更改映射。

使用Json。. NET,按照如下方式装饰medianPrice属性:

[JsonProperty(PropertyName = "median_price")]
public string medianPrice { get; set; }

我不确定JavaScriptSerializer如何成功解析您的类,因为键几乎不匹配类属性。

JavaScriperSerializer已经过时了,我建议您使用其他序列化器,例如Json。净:

public class PriceInfo
{
   [JsonProperty("success")]
   public string Success { get; set; }
   [JsonProperty("lowest_price")]
   public double LowestPrice { get; set; }
   [JsonProperty("volume")]
   public string Volume { get; set; }
   [JsonProperty("median_price")]
   public string MedianPrice { get; set; }
}

当你想要反序列化时:

PriceInfo priceInfo = JsonConvert.DeserializeObject<PriceInfo>(returnValue);

首先,正如在其他回答中提到的,您的属性名称不匹配。

所以

public class PriceInfo
{
    public string success { get; set; }
    public string lowest_price { get; set; }
    public string volume { get; set; }
    public string median_price { get; set; }
}

编辑:正如Yuval所提到的,你不能在JavaScriptSerializer中使用JsonProperty,所以你需要坚持使用json.

中的属性名称。

然后,json中有货币信息。所以你需要去掉这些:

string return_value = "{'"success'":true,'"lowest_price'":'"&#36;0.04'",'"volume'":'"3,952'",'"median_price'":'"&#36;0.02'"}";
string return_valueconverted = HttpUtility.HtmlDecode(return_value);
PriceInfo priceInfo = new JavaScriptSerializer().Deserialize<PriceInfo>(return_valueconverted);
priceInfo.lowest_price = priceInfo.lowest_price.TrimStart('$');
priceInfo.median_price = priceInfo.median_price.TrimStart('$');

如你所见,这会对这些值进行HtmlDecode,然后从值中去掉美元符号。

查看更多关于Html字符集的信息:http://www.w3.org/MarkUp/html-spec/html-spec_13.html