输入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对象的特定键,然后在alert对象中将其反序列化。
发布于 2018-06-06 17:00:18
最简单的方法是只声明外部对象,并使用足够的键到达您关心的键:
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发布于 2018-06-06 17:15:27
我建议您使用Newtonsoft.Json库来简化json数据的反序列化。
如果你想要一个的部分反序列化,例如,只将alerts属性反序列化到你的类Alert中,而不需要创建所需的整个类结构。
您可以使用以下代码:
JObject jObject = JObject.Parse(json);
var alerts = jObject["site"]["alerts"].ToObject<Alert[]>();
foreach(var item in alerts)
{
Console.WriteLine("alert: " + item.alert);
Console.WriteLine("riskcode: " + item.riskcode);
}完整的演示可用here。
发布于 2018-06-06 17:18:08
简短版本
var siteAlerts = JsonConvert.DeserializeObject<dynamic>(json).site.alerts.ToObject<Alert[]>();https://stackoverflow.com/questions/50716081
复制相似问题