使用SpringBoot,作为REST响应,我的控制器必须返回MenuDTO
的列表,该列表是SimpleMenuDTO
和TastingMenuDTO
的父类。
我正在使用ModelMapper将实体映射到DTO。
public abstract class MenuEntity {
private String name;
private String description;
private RestaurantEntity restaurant;
}
public class SimpleMenuEntity extends MenuEntity {
private final Set<MenuSectionEntity> sections = new HashSet<>();
}
public class TastingMenuEntity extends MenuEntity {
private BigDecimal price;
private final Set<ProductEntity> products = new HashSet<>();
}
public class MenuDTO {
private String name;
private String description;
private char menuType;
private Long restaurantId;
}
我该如何处理这种情况?我可以更改实体和DTO。
UPDATE这里的主要问题是如何在运行时动态映射SimpleMenuEntity
和TastingMenuEntity
的列表。
将杰克逊添加为项目依赖项:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
</dependency>
然后使用接收者可以用来区分不同菜单的@JsonTypeInfo
to output a @type
field。
@JsonTypeInfo
这可能会给JSON类似:
@type
如果您不喜欢@JsonTypeInfo(use=Id.NAME)
@JsonSubTypes({
@JsonSubTypes.Type(value=SimpleMenuDTO.class, name="Simple"),
@JsonSubTypes.Type(value=TastingMenuDTO.class, name="Tasting")
})
public class MenuDTO {
}
,请用{
// Type-specific elements
"@type" : "Tasting",
"price" : "10.0",
// Common elements
"description" : "",
"restaurantId" : 1,
"name" : ""
}
选择您自己的名字