使用JSON文件中提供的列映射信息在运行时映射两个类



我有两个这样的类。

public class InputModel
{        
public int studentid { get; set; }        
public string studentname { get; set; }       
public string studentcity { get; set; }
}
public class OutputModel
{
public int StudentIDColumn { get; set; }
public string StudentNameColumn { get; set; }
public string StudentCityColumn { get; set; }
}

现在的要求是这样的:

我将收到一个InputModel类的对象。由此,我需要创建一个OutputModel类的对象。

如果我们使用像AutoMapper这样的库,这很简单。但问题是,列到列映射信息将通过Json文件提供,如下所示:

{
"studentid": "StudentIDColumn",
"studentname": "StudentNameColumn",
"studentcity": "StudentCityColumn"
}

基于JSON映射数据,我需要在运行时映射列并生成Output类对象。

我尝试使用Automapper映射这两个类。但我不确定如何在运行时使用JSON文件来完成这项工作。

var MapperConfig = new MapperConfiguration(c => 
c.CreateMap<InputCSVModel, OutputIDMModel>()
.ForMember(dest => dest.StudentIDColumn, act => act.MapFrom(src => src.studentid))
.ForMember(dest => dest.StudentNameColumn, act => act.MapFrom(src => src.studentname))
.ForMember(dest => dest.StudentCityColumn, act => act.MapFrom(src => src.studentcity))
);

var mapper = new Mapper(MapperConfig);                
OutputIDMModel outModel = mapper.Map<OutputIDMModel>(inputModel);

我知道用Reflection可能做到这一点。但是还有更好的方法吗?

我能够读取JSOn文件,并像这样在automapper配置中传递字符串。

var MapperConfig = new MapperConfiguration(c =>
c.CreateMap<InputModel, OutputModel>()
.ForMember("StudentIDColumn", opt => opt.MapFrom("studentid"))
.ForMember("StudentNameColumn", opt => opt.MapFrom("studentname"))
.ForMember("StudentCityColumn", opt => opt.MapFrom("studentcity"))
);

最新更新