+-
c#-名称为动态时反序列化Json
我使用这个简单的API https://exchangeratesapi.io/,并使用以下uri测试: https://api.exchangeratesapi.io/history?start_at=2018-01-01&end_at=2018-03-01&symbols=SEK.
我想反序列化“费率”部分.这是一个回应样本
enter image description here

这是代码

public class ExchangeRate
{
    [JsonProperty(PropertyName = "end_at", Order = 1)]
    public DateTime EndAt { get; set; }

    [JsonProperty(PropertyName = "start_at", Order = 2)]
    public DateTime StartAt { get; set; }

    [JsonProperty(PropertyName = "rates", Order = 3)]
    public Dictionary<string, Rate> Rates { get; set; }

    [JsonProperty(PropertyName = "base", Order = 4)]
    public string Base { get; set; }
}

public class Rate
{
    [JsonProperty]
    public Dictionary<string, double> Fields{ get; set; }
}

要么

public class Rate
{
    [JsonProperty]
    public string CurrencyName { get; set; }
    [JsonProperty]
    public double CurrencyRate { get; set; }
}

我像这样对它进行杀菌

var result = Newtonsoft.Json.JsonConvert.DeserializeObject<ExchangeRateHistory>(response.Content);

我的问题是,字段为空.有人有什么建议吗?

最佳答案
如果您的键/值对不固定且数据必须可配置,则Newtonsoft.json具有要在此处使用的一项功能,即[JsonExtensionData]. Read more

Extension data is now written when an object is serialized. Reading and writing extension data makes it possible to automatically round-trip all JSON without adding every property to the .NET type you’re deserializing to. Only declare the properties you’re interested in and let extension data do the rest.

在您的情况下,费率键具有作为动态数据的值,因此您的费率类将是

public class Rate
{
    [JsonExtensionData]
    public Dictionary<string, JToken> Fields { get; set; }
}

然后,您可以将响应内容反序列化为

var result = Newtonsoft.Json.JsonConvert.DeserializeObject<ExchangeRate>(response.Content);
点击查看更多相关文章

转载注明原文:c#-名称为动态时反序列化Json - 乐贴网