Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserializing immutable record arrays using System.Text.Json

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?

like image 809
Rok Avatar asked Oct 25 '25 02:10

Rok


1 Answers

The solution is adding JsonSerializerOptions with PropertyNamingPolicy.

var options = new JsonSerializerOptions()
{
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
var result = System.Text.Json.JsonSerializer.Deserialize<ResponseFake>(data, options);
like image 53
Rok Avatar answered Oct 26 '25 17:10

Rok