我正在使用Automapper映射带有已知对象(模型)的未知(未知属性)JSON对象在c#中(使用配置文件)但无法将获取列表绑定为空。
模型
public class Student
{
public string Name {get;set;}
public string Age{get;set;}
public string RoleId{get;set;}
}
JSON
var jsonText = @"
[ {
""Code"" : ""Class786"",
""HighLevelClassOfBusinessCode"" :3
},
{
""Code"" : ""Class789"",
""HighLevelClassOfBusinessCode"" :79
}
]
";
AUTOMAPPER:
// its working when loop through list mapped one by one but i need list
public List<Student> GetNewList<Student>(JArray JsonData)
{
List<Student> dto = new List<Student>();
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<JArray, List<Student>>();
cfg.AddProfile<Student>();
});
var mapper = config.CreateMapper();
List<Student> newData = mapper.Map<List<Student>>(JsonData);
//List newData which are getting is empty
// if i used json object in loop then working fine
//foreach (var item in JsonData)
//{
// T newData= mapper.Map<T>(item);
// dto.Add(newData);
//}
return dto;
}
个人资料:为映射规则
创建的public class Student: Profile
{
public Student()
{
CreateMap<JObject, Student>()
.ForMember("Name", cfg => { cfg.MapFrom(jo => jo["Code"]); })
.ForMember("Age", cfg => { cfg.MapFrom(jo => jo["Code"]); })
.ForMember("RoleId", cfg => { cfg.MapFrom(jo => jo["HighLevelClassOfBusinessCode"]); });
}
}