0
votes

I am trying to deserialize the following JSON text into a C# class using JSON.Net.

{
"jsonrpc": "2.0",
"result": [{
    "groupid": "5",
    "name": "Discovered hosts",
    "internal": "1",
    "flags": "0"
}, {
    "groupid": "7",
    "name": "Hypervisors",
    "internal": "0",
    "flags": "0"
}, {
    "groupid": "2",
    "name": "Linux servers",
    "internal": "0",
    "flags": "0"
}, {
    "groupid": "8",
    "name": "Network Gear",
    "internal": "0",
    "flags": "0"
}, {
    "groupid": "1",
    "name": "Templates",
    "internal": "0",
    "flags": "0"
}, {
    "groupid": "6",
    "name": "Virtual machines",
    "internal": "0",
    "flags": "0"
}, {
    "groupid": "4",
    "name": "Zabbix servers",
    "internal": "0",
    "flags": "0"
}],
"id": 2

}

The classes are as follows:

    public class getHostsResponse
    {
        public string jsonrpc { get; set; }
        public List<getHostsRecord> hostlist { get; set; }
        public int id { get; set; }
    }

    public class getHostsRecord
    {
        public string groupid { get; set; }
        public string name { get; set; }
        public string internala { get; set; }
        public string flags { get; set; }
    }

The deserialize statement is:

getHostsResponse response2 = JsonConvert.DeserializeObject<getHostsResponse>(response);

The jsonrpc and id fields deserialize correctly, but the hostlist field is null.

Do I have the classes (specifically the gethostrecords) set up incorrectly to receive the deserialized stream?

Thanks.

Bryan Hunt

1

1 Answers

0
votes

Yes, the property names in your classes need to match the JSON (or else you need to use [JsonProperty] attributes on each property to indicate the JSON name where they differ).

Change the name of the hostlist property in your getHostsResponse class to result and it should start working. You've also misspelled the internal property in the getHostsRecord as internala.

Revised classes are as follows:

public class getHostsResponse
{
    public string jsonrpc { get; set; }
    public List<getHostsRecord> result { get; set; }
    public int id { get; set; }
}

public class getHostsRecord
{
    public string groupid { get; set; }
    public string name { get; set; }
    public string internal { get; set; }
    public string flags { get; set; }
}

Or, using the [JsonProperty] approach:

public class getHostsResponse
{
    public string jsonrpc { get; set; }
    [JsonProperty("result")]
    public List<getHostsRecord> hostlist { get; set; }
    public int id { get; set; }
}

public class getHostsRecord
{
    public string groupid { get; set; }
    public string name { get; set; }
    public string internal { get; set; }
    public string flags { get; set; }
}