从流中反序列化 json 得到 null 对象

Ste*_*BEG 1 c# json system.text.json

我有一个 json 文件的示例 https://pastebin.com/wL6LWbxk

{
    "rates": [{
            "code": "ATS",
            "date": "2021-03-05",
            "date_from": "2021-03-05",
            "number": 40,
            "parity": 1,
            "exchange_middle": 8.5448
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

我有以下代码:

...
var responseStream = await response.Content.ReadAsStreamAsync(); //Im getting bytes OK
var something = await JsonSerializer.DeserializeAsync<Curr>(responseStream); //object something is null
...
Run Code Online (Sandbox Code Playgroud)

我的模型看起来像:

    public class Currency
    {
        [JsonProperty("code")]
        public string Code { get; set; }

        [JsonProperty("date")]
        public DateTimeOffset Date { get; set; }

        [JsonProperty("date_from")]
        public DateTimeOffset DateFrom { get; set; }

        [JsonProperty("number")]
        public long Number { get; set; }

        [JsonProperty("parity")]
        public long Parity { get; set; }

        [JsonProperty("exchange_middle")]
        public double ExchangeMiddle { get; set; }

        [JsonProperty("exchange_buy", NullValueHandling = NullValueHandling.Ignore)]
        public double? ExchangeBuy { get; set; }

        [JsonProperty("exchange_sell", NullValueHandling = NullValueHandling.Ignore)]
        public double? ExchangeSell { get; set; }

        [JsonProperty("cash_buy", NullValueHandling = NullValueHandling.Ignore)]
        public double? CashBuy { get; set; }

        [JsonProperty("cash_sell", NullValueHandling = NullValueHandling.Ignore)]
        public double? CashSell { get; set; }
    }

    public class Curr
    {
        [JsonProperty("rates")]
        public Currency[] Rates { get; set; }
    }
Run Code Online (Sandbox Code Playgroud)

我从 json2csharp 网站完成了映射模型。

我不明白,为什么不绑定这些属性。谢谢。

Dav*_*idG 5

像 json2csharp 这样的网站会假设您正在使用 Newtonsoft JSON.Net,因此如果您使用System.Text.Json.

JsonProperty您可以通过用属性替换属性来修复代码JsonPropertyName。例如:

public class Curr
{
    [JsonPropertyName("rates")]
    public Currency[] Rates { get; set; }
}
Run Code Online (Sandbox Code Playgroud)