使用json.net反序列化JSON

时间:2016-08-18 15:38:16

标签: json.net

我正在尝试使用JSON.Net将以下JSON文本反序列化为C#类。

{
"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

}

课程如下:

    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; }
    }

反序列化语句是:

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

jsonrpc和id字段正确反序列化,但hostlist字段为空。

我是否正确设置了类(特别是gethostrecords)以接收反序列化的流?

感谢。

Bryan Hunt

1 个答案:

答案 0 :(得分:0)

是的,类中的属性名称需要与JSON匹配(否则您需要在每个属性上使用[JsonProperty]属性来指示它们不同的JSON名称。

hostlist课程中的getHostsResponse媒体资源的名称更改为result,并且应该开始工作。您还将internal中的getHostsRecord属性拼错为internala

修订课程如下:

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; }
}

或者,使用[JsonProperty]方法:

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; }
}