【发布时间】:2019-03-31 19:38:30
【问题描述】:
我们正在映射一个对象,该对象具有一个对象列表,这些对象都实现了一个父接口,但可能有不同的实现。 但是,当我们映射列表时,似乎只映射了 ParentClass 的值,而不是 child 的值。 但直接映射孩子工作正常。
public class ParentClass{
String name;
int anotherParentField;
List<ParentClass> relation;
}
public class ChildClass1 extends ParentClass{
String customCLass1Field;
}
public class ChildClass2 extends ParentClass {
int intField;
}
public class ParentClassDto{
String name;
int anotherParentField;
List<ParentClassDto> relation;
}
public class ChildClass1Dto extends ParentClassDto{
String customCLass1Field;
}
public class ChildClass2Dto extends ParentClassDto {
int intField;
}
映射器
@Mapper
public interface ParentClassMapper{
ParentClassDto convertToDto(ParentClass p);
ParentClass convertDTOToModel(ParentClassDto dto);
}
@Mapper
public interface ChildClass1Mapper implements ParentClassMapper
{
ChildClass1Dto convertToDto(ChildClass1 p);
ChildClass1 convertDTOToModel(ChildClass1Dto dto);
}
@Mapper
public interface ChildClass2Mapper implements ParentClassMapper
{
ChildClass2Dto convertToDto(ChildClass2 p);
ChildClass2 convertDTOToModel(ChildClass2Dto dto);
}
如果我们将包含 ChildClass2 和 ChildClass1 的对象 ChildClass1 映射到我们得到的列表中。
要映射的对象: 对象 ChildClass1 在 json 格式中看起来像这样:
{
"name":"myName",
"anotherParentField":"10",
"customCLass1Field":"custom name",
"relation":[
{
(This is of Object Type : ChildClass1)
"name":"firstRelationName",
"anotherParentField":"110",
"customCLass1Field":"relationcustom name"
},
{
(This is of Object Type : ChildClass2)
"name":"secondRelationName",
"anotherParentField":"110",
"intField":"4"
}
]
}
但是当我们使用上面的映射器映射到 dto 时,我们得到:
{
"name":"myName",
"anotherParentField":"10",
"customCLass1Field":"custom name",
"relation":[
{
"name":"firstRelationName",
"anotherParentField":"110",
},
{
"name":"secondRelationName",
"anotherParentField":"110",
}
]
}
没有映射子类的字段。 缺少什么?
【问题讨论】: