如何使用C#和Newtonsoft从JSON数组中提取RiskId值
解决方法:用C#和Newtonsoft提取JSON数组中的RiskId值
你的代码错误在于将JSON数组中的每个对象({}结构)误当成数组([]结构)反序列化,导致无法正确解析。以下是两种可行的解决方案:
方法一:直接使用JArray和JObject遍历(无需定义实体类)
这种方式适合快速处理简单的JSON结构:
JArray jArray = JsonConvert.DeserializeObject<JArray>(jsonstring); foreach (JObject item in jArray) { // 逐层访问嵌套属性,空传播运算符避免空引用异常 string riskId = item["Bur"]?["RiskSummary"]?["RiskId"]?.ToString() ?? string.Empty; Response.Write("RiskId : " + riskId + "<br>"); }
方法二:强类型反序列化(定义实体类)
如果JSON结构固定且需要重复使用,推荐用这种方式,编译时就能检查错误:
第一步:定义对应实体类
public class Address { public string StreetAddress1 { get; set; } public string City { get; set; } public string PostalCity { get; set; } public string State { get; set; } public string Zip { get; set; } public string Zip4 { get; set; } public string County { get; set; } } public class RiskSummary { public Address Address { get; set; } public string FPA { get; set; } public string RiskId { get; set; } public string OnsiteSurveyDate { get; set; } public string ScheduleAppliedDate { get; set; } public string YearBuilt { get; set; } } public class Comments { public List<string> GeneralComments { get; set; } public string WindComments { get; set; } public string WindLossHistory { get; set; } } public class Bur { public RiskSummary RiskSummary { get; set; } public Comments Comments { get; set; } } public class RiskItem { public Bur Bur { get; set; } public object Pdr { get; set; } public object Bov { get; set; } public string ReportCode { get; set; } }
第二步:反序列化并提取RiskId
List<RiskItem> riskItems = JsonConvert.DeserializeObject<List<RiskItem>>(jsonstring); foreach (var item in riskItems) { string riskId = item?.Bur?.RiskSummary?.RiskId ?? string.Empty; Response.Write("RiskId : " + riskId + "<br>"); }
内容的提问来源于stack exchange,提问作者user2938930
相关产品推荐
相关产品推荐

