Search code examples
c#jsondeserializationjson-deserialization

Deserialize nested JSON into C# Object


I am getting the following response from an API

    "results": {
        "wan1": {
            "id": "wan1",
            "name": "wan1",
            "alias": "",
            "mac": "00:00:00:00:00:00",
            "ip": "102.165.223.199",
            "mask": 24,
            "link": true,
            "speed": 1000.0,
            "duplex": 1,
            "tx_packets": 501850173,
            "rx_packets": 307154377,
            "tx_bytes": 442319826490,
            "rx_bytes": 234140958061,
            "tx_errors": 0,
            "rx_errors": 0
        },
        "dmz": {
            "id": "dmz",
            "name": "dmz",
            "alias": "",
            "mac": "00:00:00:00:00:00",
            "ip": "10.10.10.1",
            "mask": 24,
            "link": false,
            "speed": 0.0,
            "duplex": 0,
            "tx_packets": 0,
            "rx_packets": 0,
            "tx_bytes": 0,
            "rx_bytes": 0,
            "tx_errors": 0,
            "rx_errors": 0
        },
        "internal1": {
            "id": "internal1",
            "name": "internal1",
            "alias": "",
            "mac": "00:00:00:00:00:00",
            "ip": "0.0.0.0",
            "mask": 0,
            "link": false,
            "speed": 0.0,
            "duplex": 0,
            "tx_packets": 0,
            "rx_packets": 0,
            "tx_bytes": 0,
            "rx_bytes": 0,
            "tx_errors": 0,
            "rx_errors": 0
        }
    },
    "vdom": "root",
}

I have tried a few approaches to representing this JSON in c# objects

{
    public Dictionary<string, List<Result>> Result { get; set; }
}
public class Result
{
    public string name { get; set; }
    public string ip { get; set; }
    public int tx_bytes { get; set; }
    public int rx_bytes { get; set; }
}

And here is the method I am using to deserialize the JSON:

var result = await client.Request()
            .AppendPathSegment("api/v2/monitor/system/interface")
            .SetQueryParam("access_token", token)
            .GetJsonAsync<InterfaceResponse>(cancellationToken: cancellationToken);

It should be simple, but for some reason, I can't figure out the correct object representation, but when I debug I am getting null Thanks for the help.


Solution

  • I can see 2 issues:

    1. It's "results" not "result".
    2. "results" looks like Dictionary<string, Result> not Dictionary<string, List<Result>>.

    Additionally, if you're using System.Text.Json then casing may matter depending on your settings.