iKo*_*ode 5 .net javascript c# json deserialization
我试图在Json中解析开放汇率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);
Run Code Online (Sandbox Code Playgroud)
如果我理解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; }
}
Run Code Online (Sandbox Code Playgroud)
我希望能够通过以下方式重播"CurrencyRates汇率":
public Dictionary<string, decimal> rateDictionary { get; set; }
Run Code Online (Sandbox Code Playgroud)
但是解析器总是将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
}
}
Run Code Online (Sandbox Code Playgroud)
如果你的json是这样的:
{"key":1,"key2":2,...}
Run Code Online (Sandbox Code Playgroud)
那么你应该能够做到:
Dictionary<string, string> rateDict = serializer.Deserialize<Dictionary<string, string>>(json);
Run Code Online (Sandbox Code Playgroud)
这编译:
string json = "{\"key\":1,\"key2\":2}";
var ser = new System.Web.Script.Serialization.JavaScriptSerializer();
var dict = ser.Deserialize<Dictionary<string, int>>(json);
Run Code Online (Sandbox Code Playgroud)
你应该能够从这里自己弄清楚.
此代码适用于您的示例数据
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"];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16816 次 |
| 最近记录: |