pandemic
pandemic

Reputation: 1195

Deserialize JSON with dynamic property which contains an array to dictionary with generic class

having this JSON:

{
    "lb1": [
        {
            "ip": "10.110.2.3",
            "name": "server1",
            "enabled_state": "ENABLED"
        },
        {
            "ip": "10.110.0.1",
            "name": "server2",
            "enabled_state": "ENABLED"            
        }
    ]
    "lb2": [
        {
            "ip": "10.120.2.3",
            "name": "server3",
            "enabled_state": "ENABLED"
        }
    ]
}

where lb1 and lb2 are dynamic properties (values can be different) and I want to parse it to C# class NetworkApiResult Following few SO links how to parse json with dynamic property I ended up with below try:

NetworkApiResult:

public class NetworkApiResult<T>
{
    [JsonProperty("")]
    public Dictionary<string, IEnumerable<T>> Result { get; set; }
}

NetowrkApiNode

public class NetworkApiNode
{
    public string Name { get; set; }

    [JsonProperty("ip")]
    public string IpV4 { get; set; }

    [JsonProperty("enabled_state")]
    public bool EnabledState { get; set; }
}

How I fire and attempt to deserialize:

ExtractResult<NetworkApiResult<NetworkApiNode>>(query, @"samplePayload");

private T ExtractResult<T>(string query, string jsonContent)
    {
        var response = _client.PostAsync(query, new StringContent(jsonContent, Encoding.UTF8, "application/json")).Result;
        using (Stream s = response.Content.ReadAsStreamAsync().Result)
        using (StreamReader sr = new StreamReader(s))
        using (JsonReader reader = new JsonTextReader(sr))
        {
            JsonSerializer serializer = new JsonSerializer();

            return serializer.Deserialize<T>(reader);
        }
    }

any idea what am I doing wrong here? Result property of NetworkApiResult is null

Upvotes: 0

Views: 59

Answers (1)

Anu Viswan
Anu Viswan

Reputation: 18163

Based on the Json shared, you need to Deserialize using

serializer.Deserialize<Dictionary<string,List<NetworkApiNode>>>(reader);

You do NOT need the wrapping NetworkApiResult<T>.

However, please note you also need a change in NetworkApiNode. The "enabled_state" is a String and not a boolean. If you need to convert the value to a boolean value, you could use a readonly property which checks the deserialized State for the value as seen in the code below.

public class NetworkApiNode
{
    [JsonProperty("name")]
    public string Name { get; set; }

    [JsonProperty("ip")]
    public string IpV4 { get; set; }

    public bool EnabledState => State.Equals("ENABLED");

    [JsonProperty("enabled_state")]
    public string State{get;set;}
}

Sample Output

enter image description here

Upvotes: 2

Related Questions