完成JSON的新手-这是我第一次使用C#尝试JSON。
我有一条从HTTP get请求返回的记录。
var exchRateData = Get($"https://api.exchangeratesapi.io/2018-10-30?base=EUR&symbols=AUD");
返回:
{"date":"2018-10-30","rates":{"AUD":1.6025},"base":"EUR"}
。
AUD和1.6025值都是GET请求中的变量。因此,GET请求可以是针对SGD或INR的请求,并在其中返回:
{"date":"2018-10-30","rates":{"SGD":0.0187977737},"base":"INR"}
总是返回带有级别的一条记录,就像上面的两个示例一样。
我要访问的是第二级值
即{"AUD":1.6025} or {"SGD":0.0187977737}
我尝试过:
var jsonResult = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(exchRateData);
foreach (var keyValue in jsonResult)
{
try
{
LblGetValues.Text = LblGetValues.Text + "Key: " + keyValue.Key + " Value:" + keyValue.Value + "<br>";
if (keyValue.Key == "date")
LblDate.Text = keyValue.Value;
//This is where I get stuck.
if (keyValue.Key == "rates")
{
// I would like to be able to do this here :
//string currencyCode = "AUD" (or "SGD" if second GET request)
//double currencyRate = 1.6025 (or 0.0187977737 if second GET request)
//JArray secondLevel = new JArray("rates");
// LblRate.Text = keyValue.Value.ToString();
}
if (keyValue.Key == "base")
LblBase.Text = keyValue.Value;
}
catch (Exception errMsg)
{
LblMsg.Text = errMsg.Message + errMsg.StackTrace;
}
}
请帮助。...
答案 0 :(得分:2)
我建议使用JSON.NET
在这里,您将反序列化JSON字符串到c#模型类中
您的模型类看起来像这样Model Generated using json2csharp
public class Rates
{
[JsonProperty(PropertyName = "fieldName")]
public double currency { get; set; }
}
public class RootObject
{
public string date { get; set; }
public Rates rates { get; set; }
public string @base { get; set; }
}
这就是您使用JSON.NET反序列化的方式
// THis works for normal secanario but it won't work for you
var exchangeRates = JsonConvert.DeserializeObject<RootObject>("Your Json String goes here");
但是您的JSON场景有点复杂,因此您必须使用 CustomContractResolver
以下是示例
ContractResolver类
internal class CustomContractResolver : DefaultContractResolver
{
public CustomContractResolver(string fieldName)
{
FieldName = fieldName;
}
public string FieldName { get; set; }
protected override string ResolvePropertyName(string propertyName)
{
return propertyName == "fieldName" ? FieldName : base.ResolvePropertyName(propertyName);
}
}
如何使用此设置
var settings = new JsonSerializerSettings
{
DefaultValueHandling = DefaultValueHandling.Ignore,
MissingMemberHandling = MissingMemberHandling.Ignore,
ContractResolver = new CustomContractResolver("Pass Your currency here")
};
// Make Http Calls here and replace returned string in below method
var data = JsonConvert.DeserializeObject<RootObject>("Your JSON String", setting);
// Here You can access your currency rates
double currencyRate = data.currency;
答案 1 :(得分:1)
public class Rates
{
public double AUD { get; set; }
}
public class ObjectCurrency
{
public string date { get; set; }
public Rates rates { get; set; }
public string @base { get; set; }
}
var data= JsonConvert.DeserializeObject<ObjectCurrency>(exchRateData);
答案 2 :(得分:1)
如果只有一个速率(这是OP想要的),则可接受的解决方案可以很好地工作,但不能以超过1个速率的方式工作。另外,它还增加了额外的复杂性,可以通过使用Dictionary
来避免(见下文)。
示例-以下请求(AUD
,USD
,GBP
)
https://api.exchangeratesapi.io/2018-10-30?base=EUR&symbols=AUD,USD,GBP
将返回以下json:
{“ date”:“ 2018-10-30”,“ rates”:{“ USD”:1.1372,“ GBP”:0.89148,“ AUD”:1.6025},“ base”:“ EUR”} >
您可以使用以下C#类反序列化json字符串:
public class ExchangeRate
{
[JsonProperty("date")]
public string Date { get; set; }
[JsonProperty("rates")]
public Dictionary<string, decimal> Rate { get; set; }
[JsonProperty("base")]
public string Base { get; set; }
}
反序列化json字符串:
string json = @"{""date"":""2018-10-30"",""rates"":{""USD"":1.1372,""GBP"":0.89148,""AUD"":1.6025},""base"":""EUR""}";
ExchangeRate rate = JsonConvert.DeserializeObject<ExchangeRate>(json);
结果: