Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Deserialize none standard Json with System.Text.Json

I have to deserialize into a object the following json string:

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

Into a model, for instance like the following one :

public class OrderInfo
{
    public string OrderId { get; set; }
    public Info Info { get; set; }
}

public class Info
{
    public decimal avg_price { get; set; }

    public decimal cost { get; set; }

    public decimal fee { get; set; }

    public decimal vol_exec { get; set; }
}

I have tried without success with this kind of code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var nodes = JsonNode.Parse(jsonString);
foreach (var order in nodes[0].AsArray())
{
  // ??
}

Or :

var info = JsonSerializer.Deserialize<OrderInfo>(jsonString);

How can I handle a Json without clear {"Property": "name"} structure by using System.Text.Json framework ?

>Solution :

First of all, your Info class isn’t correct. The values coming in the JSON are strings since they are wrapped with double quotes. So it should look like this:

public class Info
{
    public string avg_price { get; set; }
    public string cost { get; set; }
    public string fee { get; set; }
    public string vol_exec { get; set; }
}

Secondly, this JSON is actually an array of arrays.

Thirdly, you can use a Dictionary to cope with the changing property names.

So to deserialise, you can do something like this:

var result = JsonSerializer.Deserialize<Dictionary<string, Info>[][]>(jsonString);

foreach (var element in result)
{
    foreach (var innerElement in element)
    {
        foreach(var dictionaryItem in innerElement)
        {
            var key = dictionaryItem.Key;
            var info = dictionaryItem.Value;
            
            var avgPrice = info.avg_price;
        }

    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading