输入JSON文件:

{
    "@version": "2.7.0",
    "@generated": "Wed, 30 May 2018 17:23:14",
    "site": {
        "@name": "http://google.com",
        "@host": "google.com",
        "@port": "80",
        "@ssl": "false",
        "alerts": [
            {

                "alert": "X-Content-Type-Options Header Missing",
                "name": "X-Content-Type-Options Header Missing",
                "riskcode": "1",
                "confidence": "2",
                "riskdesc": "Low (Medium)",
                "desc": "<p>The Anti-MIME-Sniffing header X-Content-Type-Options was not set to 'nosniff'. This allows older versions of Internet Explorer and Chrome to perform MIME-sniffing on the response body, potentially causing the response body to be interpreted and displayed as a content type other than the declared content type. Current (early 2014) and legacy versions of Firefox will use the declared content type (if one is set), rather than performing MIME-sniffing.</p>",
                "instances": [
                    {
                        "uri": "http://google.com",
                        "method": "GET",
                        "param": "X-Content-Type-Options"
                    }
                ],
                "wascid": "15",
                "sourceid": "3"
            }

        ]
    }
}


预期产量:
列出警报;

哪里:

public class Alert
{
    public string alert;
    public string riskcode;
}


我想获取json对象的特定键,然后在警报对象中反序列化它。

最佳答案

最简单的方法是仅使用足够的键声明外部对象以达到您关心的键:

public class Alert
{
    public string alert;
    public string riskcode;
}

public class SiteAlerts
{
    public Site site { get; set; }
}

public class Site
{
    public List<Alert> alerts { get; } = new List<Alert>();
}


然后,您可以简单地反序列化:

var siteAlerts = JsonConvert.DeserializeObject<SiteAlerts>(json);
var alerts = siteAlerts.site.alerts; // no error-checking here

09-10 11:40
查看更多