我在JSON中有这个(数据更改以保护有罪的人):
{"members" : [{"Name":"Mick Jagger","Status":"ACTIVE","ExpireDate":"11/19/2015","TermType":"MONTH","State":"NY","Address2":"","Address1":"123 Anystreet","Type":"PREMIUM","EmailAddress":"mick.jagger@stickyfingers.com","Zip":"12345","Country":"US","City":"New York","Term":"12"},
{"Name":"Keith Richards","Status":"ACTIVE","ExpireDate":"11/19/2015","TermType":"ANNUAL","State":"CT","Address2":"","Address1":"5150 Main St","Type":"PREMIUM","EmailAddress":"keef@xpensivewinos.net","Zip":"45678","Country":"US","City":"New York","Term":"1"}]}
我有这个课程:
public class Member
{
public string Company_Num { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Status { get; set; }
public string ExpireDate { get; set; }
public string TermType { get; set; }
public string State { get; set; }
public string Address2 { get; set; }
public string Address1 { get; set; }
public string Type { get; set; }
public string EmailAddress { get; set; }
public string Zip { get; set; }
public string Country { get; set; }
public string City { get; set; }
public string Term { get; set; }
}
public class MemberList
{
public List<Member> members { get; set; }
}
当我将其反序列化为数据集时,它运行良好。但。。。
当我生成 MemberList 类时,我忘记了 JSON 中的"Name"需要拆分为 FirstName 和 LastName。有没有办法反序列化 JSON 对象并同时拆分"名称"?(所以名字是"基思",姓氏是"理查兹"等等。
这是我将其反序列化为成员列表时的外观:
public static MemberList memList()
{
WebClient atv = new WebClient();
var data = atv.DownloadString("https://www.somewebsvc.com/memberships");
MemberList m = Newtonsoft.Json.JsonConvert.DeserializeObject<MemberList>(data);
return m;
}
一个可能的解决方案是在模型中创建字段,这些字段将在获取它们时返回所需的值:
public class Member
{
//other properties
private string _lastName;
public string LastName {get
{
if (_lastName == null)
_lastName = Name.Split(new [] {' '}, 2)[1];
return _lastName;
}}
private string _firstName;
public string FirstName {get
{
if (_firstName== null)
_firstName= Name.Split(new [] {' '}, 2)[0];
return _firstName;
}}
}
这是一个在你提出问题后立即弄清楚的情况。
我向成员添加了一个 Name 属性,然后在代码返回列表之前添加了一个 foreach 循环。所以现在它看起来像这样:
public static MemberList memList()
{
WebClient atv = new WebClient();
var data = atv.DownloadString("https://www.somewebsvc.com/memberships");
MemberList m = Newtonsoft.Json.JsonConvert.DeserializeObject<MemberList>(data);
foreach (Member mb in m.members)
{
string[] names = mb.Name.Split(new char[] { ' ' }, 2);
mb.FirstName = names[0];
mb.LastName = names[1];
}
return m;
}
正如评论中指出的那样,当你必须解析"Mary Ann Smith"或"Nigel Baxter Taylor"时,这是非常丑陋的,但你几乎可以在那里插入任何字符串解析逻辑,它会起作用。客户端只想要名字的第一个单词。如果这让他们高兴,我不会争论。