我在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对象并同时拆分“名称”? (所以FirstName是“Keith”,LastName是“Richards”等等。)
以下是我将其反序列化为MemberList时的外观:
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;
}
答案 0 :(得分:2)
一种可能的解决方案是在模型中创建一个字段,在获取它们时返回所需的值:
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;
}}
}
答案 1 :(得分:0)
这是一个在你提出问题时就把它弄清楚的情况。
我向Members添加了一个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;
}
正如评论中所指出的那样,当你必须解析玛丽安史密斯&#34;或者&#34; Nigel Baxter Taylor&#34;,但你可以在那里插入任何字符串解析逻辑,它可以工作。客户只需要名字的第一个单词作为名字。如果这让他们开心,我就不会争辩。