我正在读取JSON文件
"data": [
{
"workPhaseID": 1,
"workPhaseName": "Phase 1",
"millID": 1,
"millName": "Mill 1",
},
{
"workPhaseID": 2,
"workPhaseName": "Phase 2",
"millID": 1,
"millName": "Mill 1",
},
... ergo there is a list of mills and each mill contains a set of work phases
]
转换为简单对象列表。我想将简单对象列表转换为复杂对象列表,以便主要对象是工厂,工厂将包含与其相关的工作阶段列表。然后,我可以将其作为新的JSON推出。
我可以找到很多有关如何使用自动映射器将复杂对象展平为简单对象的示例,并且我可以在stackoverflow中找到一些简单->复杂映射的示例,但是没有一个与我的情况完全匹配,我可以信息拼凑得不够完整,无法完成我的具体案例,因此将不胜感激。
以下是课程:
public class WorkPhaseDO
{
public short WorkPhaseID { get; set; }
public string WorkPhaseName { get; set; }
public byte? MillID { get; set; }
public string MillName { get; set; }
}
public class MillDO
{
public string MillName { get; set; }
public byte? MillID { get; set; }
public List<WorkPhaseForMillDO> Lines { get; set; }
}
public class WorkPhaseForMillDO
{
public short WorkPhaseID { get; set; }
public string WorkPhaseName { get; set; }
}
Ergo,我想将WorkPhaseDO映射到MillDO
我知道,如果我没有列表,而MillDO的最后一行是“ public WorkPhaseForMillDO Lines {get; set;}”,那么此映射将起作用:
Mapper.Initialize(config =>
{
config.CreateMap<WorkPhaseDO, MillDO>()
.ForMember(dest => dest.Lines, act => act.MapFrom(src => new WorkPhaseForMillDO()
{
WorkPhaseID = src.WorkPhaseID,
WorkPhaseName = src.WorkPhaseName,
}));
});
但是这还不够,我需要在每个磨机对象下都有一个工作阶段列表。
因此,最终结果应该是MillDO对象的列表(1个对象= 1 mill),并且每个MillDO应该包含WorkPhaseForMillDO对象的列表。 WorkPhaseForMillDO中的workPhaseID是一个唯一的数字,workPhaseName不一定是唯一的。
如果它有助于理解我想要的对象结构,则生成的JSON应该如下所示:
[{
"millId": 1,
"millName": "Mill 1",
"workPhases": [{
"workPhaseId": 1,
"workPhaseName": "Phase 1"
}, {
"workPhaseId": 2,
"workPhaseName": "Phase 2"
},
...
}],
"millId": 2,
"millName": "Mill 2",
"workPhases": [{
"workPhaseId": 5,
"workPhaseName": "Phase 1"
}, {
"workPhaseId": 6,
"workPhaseName": "Phase 6"
},
...
}]
...
}]