我正在使用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.net库从json字符串中的CustomerAddress.City
属性填充City
吗?
答案 0 :(得分:1)
直接 - 没有。
但应该有可能实现这一目标,例如:这是一次尝试(假设你不能改变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
}
其他可能性:
Address
对象;