我使用的是Json.net api JsonConvert.PopulateObject
,它接受两个参数,首先是json字符串,其次是您想要填充的实际对象。
我要填充的对象的结构是
internal class Customer
{
public Customer()
{
this.CustomerAddress = new Address();
}
public string Name { get; set; }
public Address CustomerAddress { get; set; }
}
public class Address
{
public string State { get; set; }
public string City { get; set; }
public string ZipCode { get; set; }
}
我的json字符串是
{
"Name":"Jack",
"State":"ABC",
"City":"XX",
"ZipCode":"098"
}
现在Name
属性被填充,因为它存在于json字符串中,但CustomerAddress
没有被填充。是否有任何方法,我可以告诉json字符串中City
属性填充CustomerAddress.City
的Json.net库?
直接-不。
但这应该是可能实现的,例如,这里是一个尝试(假设你不能改变json):
class Customer
{
public string Name { get; set; }
public Address CustomerAddress { get; set; } = new Address(); // initial value
// private property used to get value from json
// attribute is needed to use not-matching names (e.g. if Customer already have City)
[JsonProperty(nameof(Address.City))]
string _city
{
set { CustomerAddress.City = value; }
}
// ... same for other properties of Address
}
其他可能性:
- 更改json格式以包含
Address
对象; - 自定义序列化(例如使用binder序列化伪类型并将其转换为所需);
- …(应该更多).