c# json deserialize complex structures

45 Views Asked by At

I have a json document like this:

[
    {
        "TimerDuration": "1",
        "UpdateDate": "a",
        "DataBinding": [
            {
                "Name": "a",
                "Path": "b"
            },
            {
                "Name": "a",
                "Path": "b"
            }
        ]
    }
]

The classes behind this are:

internal class Settings
{
    public String TimerDuration;
    public String UpdateDate;
    public List<DataBindings> DataBinding = new List<DataBindings>();
}

and:

internal class DataBindings
{
    public String Name;
    public String Path;
}

I want to deserialize the document into strings, I can use. How can I do this?

1

There are 1 best solutions below

1
Power Mouse On

you have list of objects in your JSON as []. also please be more specific what did you mean to [deserialize the document into strings]??? as i understood you did not create class structure correctly instead of properties you have fields.

there are 2 approaches. with Newtonsoft and with System.Text.Json

void Main()
{
    string json = "[{\"TimerDuration\":\"1\",\"UpdateDate\":\"a\",\"DataBinding\":[{\"Name\":\"a\",\"Path\":\"b\"},{\"Name\":\"a\",\"Path\":\"b\"}]}]";
    var result = JsonConvert.DeserializeObject<List<Settings>>(json).Dump();

    var sr = System.Text.Json.JsonSerializer
            .Deserialize<Settings[]>(json, new System.Text.Json.JsonSerializerOptions
                                                {PropertyNameCaseInsensitive = true})
            .Dump();
}


internal class Settings
{
    public string TimerDuration { get; set;}
    public string UpdateDate { get; set;}
    public List<DataBindings> DataBinding { get; set;}
    public Settings(){ DataBinding = new List<DataBindings>(); }
}


internal class DataBindings
{
    public string Name { get; set;}
    public string Path { get; set;}
}


enter image description here