JavaScriptSerializer.Deserialize()转换为字典
本文关键字:字典 转换 Deserialize JavaScriptSerializer | 更新日期: 2023-09-27 18:24:14
我试图在JSON中解析Open Exchange Rates JSON,我使用的方法是:
HttpWebRequest webRequest = GetWebRequest("http://openexchangerates.org/latest.json");
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
string jsonResponse = string.Empty;
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
jsonResponse = sr.ReadToEnd();
}
var serializer = new JavaScriptSerializer();
CurrencyRateResponse rateResponse = serializer.Deserialize<CurrencyRateResponse>(jsonResponse);
如果我正确理解JavaScriptSerializer.Deserialize,我需要定义和对象来将Json转换为。
我可以使用以下数据类型成功地序列化它:
public class CurrencyRateResponse
{
public string disclaimer { get; set; }
public string license { get; set; }
public string timestamp { get; set; }
public string basePrice { get; set; }
public CurrencyRates rates { get; set; }
}
public class CurrencyRates
{
public string AED { get; set; }
public string AFN { get; set; }
public string ALL { get; set; }
public string AMD { get; set; }
}
我希望能够用类似的东西重播"CurrencyRates"
public Dictionary<string, decimal> rateDictionary { get; set; }
但是解析器总是将rateDictionary返回为null。你知道这是否可能,或者你有更好的解决方案吗?
编辑:Json看起来是这样的:
{
"disclaimer": "this is the disclaimer",
"license": "Data collected from various providers with public-facing APIs",
"timestamp": 1328880864,
"base": "USD",
"rates": {
"AED": 3.6731,
"AFN": 49.200001,
"ALL": 105.589996,
"AMD": 388.690002,
"ANG": 1.79
}
}
如果您的json类似于:
{"key":1,"key2":2,...}
那么你应该能够做到:
Dictionary<string, string> rateDict = serializer.Deserialize<Dictionary<string, string>>(json);
这编译:
string json = "{'"key'":1,'"key2'":2}";
var ser = new System.Web.Script.Serialization.JavaScriptSerializer();
var dict = ser.Deserialize<Dictionary<string, int>>(json);
你应该能够从这里自己弄清楚。
此代码适用于您的样本数据
public class CurrencyRateResponse
{
public string disclaimer { get; set; }
public string license { get; set; }
public string timestamp { get; set; }
public string @base { get; set; }
public Dictionary<string,decimal> rates { get; set; }
}
JavaScriptSerializer ser = new JavaScriptSerializer();
var obj = ser.Deserialize<CurrencyRateResponse>(json);
var rate = obj.rates["AMD"];
Below code will work fine, CurrencyRates is collection so that by using List we can take all reates.
This should work!!
public class CurrencyRateResponse
{
public string disclaimer { get; set; }
public string license { get; set; }
public string timestamp { get; set; }
public string basePrice { get; set; }
public List<CurrencyRates> rates { get; set; }
}
public class CurrencyRates
{
public string AED { get; set; }
public string AFN { get; set; }
public string ALL { get; set; }
public string AMD { get; set; }
}
JavaScriptSerializer ser = new JavaScriptSerializer();
var obj = ser.Deserialize<CurrencyRateResponse>(json);
var rate = obj.rates["AMD"];