问题描述
有人可以帮助我将api https://www.freeforexapi.com/api/live?pairs=EURUSD,GBPUSD的JSON反序列化为C#对象吗?我尝试了很多在网上找到的方法和示例,但似乎不起作用
解决方法
例如,使用newtonsoft json 创建响应类
public class EURUSD {
public double rate { get; set; }
public int timestamp { get; set; }
}
public class GBPUSD {
public double rate { get; set; }
public int timestamp { get; set; }
}
public class Rates {
public EURUSD EURUSD { get; set; }
public GBPUSD GBPUSD { get; set; }
}
public class Root {
public Rates rates { get; set; }
public int code { get; set; }
}
然后反序列化响应,例如
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
您可以使用json2csharp网站轻松生成这样的类^
,这里的费率是Map,所以Response C#类看起来像这样:
public class Response
{
public Dictionary<string,Rate> Rates{get;set;}
public int Code {get;set;}
}
public class Rate
{
public double Rate { get; set; }
public long TimeStamp { get; set; }
}
要反序列化:
var obj = JsonConvert.DeserializeObject<Response>(jsonObject);