Let say we have theese records:
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; }
}
And this XUnit test:
[Fact]
public void QuoteChartResponseFakeDeserializationTest()
{
var data = @"{""quotes"": [ { ""o"": { ""bid"": 1.1 } } ] }";
var result = System.Text.Json.JsonSerializer.Deserialize<ResponseFake>(data);
result.Quotes.Should().NotBeEmpty();
}
Test fail with error "Expected result.Quotes not to be empty, but found ."
What should I do to get Quotes populated?
The solution is adding JsonSerializerOptions with PropertyNamingPolicy.
var options = new JsonSerializerOptions()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
var result = System.Text.Json.JsonSerializer.Deserialize<ResponseFake>(data, options);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With