使用JSON.NET将JSON数据反序列化为C#我对于处理C#和JSON数据相对来说还是新手,并且正在寻求指导。我使用的是C#3.0和.NET3.5SP1以及JSON.NET 3.5r6。我有一个定义好的C#类,需要从JSON结构中填充。但是,并非从Web服务检索的条目的每个JSON结构都包含在C#类中定义的所有可能的属性。我一直在做的事情似乎是错误的、艰难的,我只是从JObject中逐个选择每个值,并将字符串转换为所需的类属性。JsonSerializer serializer = new JsonSerializer();var o = (JObject)serializer.Deserialize(myjsondata);MyAccount.EmployeeID =
(string)o["employeeid"][0];将JSON结构反序列化为C#类并处理JSON源中可能丢失的数据的最佳方法是什么?我的类被定义为: public class MyAccount
{
[JsonProperty(PropertyName = "username")]
public string UserID { get; set; }
[JsonProperty(PropertyName = "givenname")]
public string GivenName { get; set; }
[JsonProperty(PropertyName = "sn")]
public string Surname { get; set; }
[JsonProperty(PropertyName = "passwordexpired")]
public DateTime PasswordExpire { get; set; }
[JsonProperty(PropertyName = "primaryaffiliation")]
public string PrimaryAffiliation { get; set; }
[JsonProperty(PropertyName = "affiliation")]
public string[] Affiliation { get; set; }
[JsonProperty(PropertyName = "affiliationstatus")]
public string AffiliationStatus { get; set; }
[JsonProperty(PropertyName = "affiliationmodifytimestamp")]
public DateTime AffiliationLastModified { get; set; }
[JsonProperty(PropertyName = "employeeid")]
public string EmployeeID { get; set; }
[JsonProperty(PropertyName = "accountstatus")]
public string AccountStatus { get; set; }
[JsonProperty(PropertyName = "accountstatusexpiration")]
public DateTime AccountStatusExpiration { get; set; }
[JsonProperty(PropertyName = "accountstatusexpmaxdate")]
public DateTime AccountStatusExpirationMaxDate { get; set; }
[JsonProperty(PropertyName = "accountstatusmodifytimestamp")]
public DateTime AccountStatusModified { get; set; }
[JsonProperty(PropertyName = "accountstatusexpnotice")]
public string AccountStatusExpNotice { get; set; }
}
3 回答
- 3 回答
- 0 关注
- 1037 浏览
添加回答
举报
0/150
提交
取消