前言:我知道JSON.NET但我不能使用它(客户机)。
我需要将http://api.fixer.io/latest?base=USD返回的JSON解析为3列,date,currencyCode和rate。问题在于嵌套的“费率”部分。货币代码是第一个元素的名称,这意味着我不能使用“key”和“value”属性。我知道的唯一方法是硬编码每个可能的货币代码,这是我目前在下面的代码中。我希望能够使用键/值对同时提取代码/速率。
JSON:
{"base":"USD",
"date":"2016-07-12",
"rates": {
"AUD":1.3101,
"BGN":1.7633,
"BRL":3.2829,
"CAD":1.3029,
etc....}
}
到目前为止我的代码:
static void Main(string[] args)
{
var curDate = "2001-01-01";
var URL = @"http://api.fixer.io/" + curDate + "?base=USD";
Console.WriteLine(URL);
//WebRequest wrGetURL = WebRequest.Create(URL);
var text = "";
//wrGetURL.ContentType = "application/json; charset=utf-8";
HttpWebRequest httpWebRequest = System.Net.WebRequest.Create(URL) as HttpWebRequest;
using (HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse)
{
if (httpWebResponse.StatusCode != HttpStatusCode.OK)
{
throw new Exception(string.Format("Server error (HTTP {0}: {1}).",
httpWebResponse.StatusCode, httpWebResponse.StatusDescription));
}
Stream stream = httpWebResponse.GetResponseStream();
DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(JSONRead));
JSONRead objResponse = (JSONRead)dataContractJsonSerializer.ReadObject(stream);
Console.WriteLine(objResponse.rates.AUD);
}
Console.ReadLine();
}
[DataContract]
public class JSONRead
{
[DataMember(Name = "date")]
public string date { get; set; }
[DataMember(Name = "rates")]
public Rates rates { get; set; }
[DataMember(Name = "base")]
public string bases { get; set; }
}
[DataContract]
public class Rates
{
[DataMember(Name = "AUD")]
public string AUD { get; set; }
//[DataMember(Name = "key")]
//public string key { get; set; }
//[DataMember(Name = "value")]
//public string value { get; set; }
}
我想要回归:
Date Code Rate
2016-07-12 AUD 1.3101
2016-07-12 GBN 1.7633
etc...
答案 0 :(得分:0)
我必须使用DataContractJsonSerializerSettings
并将UseSimpleDictionaryFormat
设置为true
。然后它正确地将嵌套对象读入Dictionary对象。感谢@Plutonix的帮助。