Home > Software design >  Problem to define the data model with Text.Json and source generator
Problem to define the data model with Text.Json and source generator

Time:08-06

I would like to use Text.Json with source generator.

Given the following json string:

var json = @"[[{""OU2CJ3-UBRYG-KCPVS5"":{""cost"":""27187.08000"",""vol_exec"":""3.40000000"",""fee"":""27.18708"",""avg_price"":""7996.20000""}}]]";

I tried with the following data model and several flavors, but it seems incorrect as the deserialize output lead to null data. I don't see how to handle the double array definition in this scenario.

[JsonSerializable(typeof(OpenOrder), GenerationMode = JsonSourceGenerationMode.Default)]
public partial class MyContext: JsonSerializerContext
{
}   

public partial class OpenOrder
{
    public  Dictionary<string, OpenOrderFrame>  OrderFrame { get; set; }
}

public partial class OpenOrderFrame
{
    public string fee { get; set; }

    public string cost { get; set; }

    public string vol_exec { get; set; }

    public string avg_price { get; set; }
} 

var result = JsonSerializer.Deserialize(json, MyContext.Default.OpenOrder);

No exception is thrown but result contains null data. What is the correct model definition that match the input json string ?

CodePudding user response:

Your type structure does not represent the json correctly, you need Dictionary<string, Tests.OpenOrderFrame> in double nested collection (though do not know why the code have not produced any errors for you - for me it did). For example next worked for me:

[JsonSerializable(typeof(Dictionary<string, OpenOrderFrame>[][]), GenerationMode = JsonSourceGenerationMode.Default)]
public partial class MyContext: JsonSerializerContext
{
}

var result = JsonSerializer.Deserialize(json, MyContext.Default.DictionaryStringOpenOrderFrameArrayArray);
  • Related