gpt4 book ai didi

c# - 使用 System.Text.Json 反序列化不可变记录数组

转载 作者:行者123 更新时间:2023-12-02 02:17:14 25 4
gpt4 key购买 nike

假设我们有这些记录:

public record ResponseFake
{
[JsonConstructor]
public ResponseFake(OhlcFake[] quotes)
{
Quotes = quotes;
}
public OhlcFake[] Quotes { get; }
}
public record OhlcFake
{
[JsonConstructor]
public OhlcFake(QuoteFake o)
{
O = o;
}
public QuoteFake O { get; }
}
public record QuoteFake
{
[JsonConstructor]
public QuoteFake(decimal bid)
{
Bid = bid;
}
public decimal Bid { get; }
}

还有这个 XUnit 测试:

[Fact]
public void QuoteChartResponseFakeDeserializationTest()
{
var data = @"{""quotes"": [ { ""o"": { ""bid"": 1.1 } } ] }";

var result = System.Text.Json.JsonSerializer.Deserialize<ResponseFake>(data);

result.Quotes.Should().NotBeEmpty();
}

测试失败,出现错误“预期结果。引号不是空的,但找到了。”

我应该怎么做才能填充 Quotes

最佳答案

解决方案是添加 JsonSerializerOptionsPropertyNamingPolicy

var options = new JsonSerializerOptions()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
var result = System.Text.Json.JsonSerializer.Deserialize<ResponseFake>(data, options);

关于c# - 使用 System.Text.Json 反序列化不可变记录数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66981207/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com