【发布时间】:2021-10-20 07:51:08
【问题描述】:
为了演示我的问题,让我们考虑有 3 个实体:
public class Employee
{
public string Name { get; set; }
public Department Department { get; set; }
public Address Address { get; set; }
}
public class Department
{
public string Id { get; set; }
public string Name { get; set; }
}
public class Address
{
public string City { get; set; }
public string State { get; set; }
public string ZipCode { get; set; }
}
还有属性路径列表及其值:
{
"Name":"Abhishek",
"Deparment.Id":"28699787678679",
"Deparment.Name":"IT",
"Address.City":"SomeCity",
"Address.State":"SomeState",
"Address.ZipCode":"29220"
}
最后,我想使用这些键值对列表生成员工对象。 为了演示我的问题,我在这里使用了一个非常简单的“员工”实体。但是,我需要将 100 个这样的键值对转换为一个复杂的对象,因此我不考虑手动映射每个属性的选项。
只要这个复杂实体中的所有属性都是字符串属性。我们如何动态地实现这一点。
我尝试通过循环每个属性路径并使用 c# 反射以以下方式动态设置属性值来解决它:
(灵感来自https://stackoverflow.com/a/12294308/8588207)
private void SetProperty(string compoundProperty, object target, object value)
{
string[] bits = compoundProperty.Split('.');
PropertyInfo propertyToSet = null;
Type objectType = null;
object tempObject = null;
for (int i = 0; i < bits.Length - 1; i++)
{
if (tempObject == null)
tempObject = target;
propertyToSet = tempObject.GetType().GetProperty(bits[i]);
objectType = propertyToSet.PropertyType;
tempObject = propertyToSet.GetValue(tempObject, null);
if (tempObject == null && objectType != null)
{
tempObject = Activator.CreateInstance(objectType);
}
}
propertyToSet = tempObject.GetType().GetProperty(bits.Last());
if (propertyToSet != null && propertyToSet.CanWrite)
propertyToSet.SetValue(target, value, null);
}
【问题讨论】:
-
这可能与Json序列化有关吗?在属性上使用属性 [JsonPropertyName("Deparment.Name")] ?
-
@Hazrelle 试过这样做,但没有运气。
-
也许我们可以提供更多信息以提供更好的帮助。您拥有的更多示例 json 数据以及如何使用您拥有的信息填写
Employee。 -
Json 数据
{ "Name":"Abhishek", "Deparment.Id":"28699787678679", "Deparment.Name":"IT", "Address.City":"SomeCity", "Address.State":"SomeState", "Address.ZipCode":"29220", "Project.Address.City":"SomeOtherCity", }转换为下面的Employee对象var employee = new Employee { Name = "Abhishek", Deparment = new Deparment { Id = "28699787678679", Name = "IT" }, Address = new Address { City = "SomeCity", State = "SomeState" }, Project = new Project { Address = new Address { City = "SomeOtherCity" } } } -
@Hazrelle 这样就够了吗?
标签: c# reflection