【发布时间】:2018-11-20 23:10:34
【问题描述】:
如何正确映射具有相同父级的不同类
spring DTO jackson 对象
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.PROPERTY,
property = "type",
)
@JsonSubTypes(value = {
@JsonSubTypes.Type(value = B.class, name = "TypeB"),
@JsonSubTypes.Type(value = C.class, name = "TypeC")
})
abstract class A {
Type type;
String id;
}
class B extends A {
String name;
}
class C extends A {
String description;
}
实体类包含所有字段
class myEntity {
Type type;
String id;
String name;
String description;
}
MapStruct 映射器
public abstract class IntegrationMapper {
public A toDto(MyEntity myEntity);
public MyEntity fromDto(A integrationDTO)
}
如何在 toDto 中创建不同的实例 B 或 C 取决于 type 值?
我就是这么用的
public abstract class IntegrationMapper {
public A toDto(MyEntity myEntity) {
if(myEntity.type == TypeB) {
return toB(myEntity);
} else if (myEntity.type == TypeC) {
return toC(myEntity);
}
}
public MyEntity fromDto(A a) {
if(a instanceOf B) {
return fromDto((B) a);
} else if (a instanceOf C) {
return fromDto((C) a);
}
}
protected B toB(MyEntity myEntity);
protected C toC(MyEntity myEntity);
protected MyEntity fromDto(B c);
protected MyEntity fromDto(C c);
}
但我怀疑使用 ObjectFactory 或类似的东西可以做得更好
避免长 if 语句 并为 A
的每个新子级创建新方法【问题讨论】:
标签: java spring jackson jackson2 mapstruct