我有接受 BaseDto 的端点:
@RequestMapping(
method = RequestMethod.POST,
value = "/path",
produces = { "application/json" },
consumes = { "application/json" }
)
fun foo(@Valid @RequestBody dto:BaseDto ):ResponseEntity<?> {
...
}
Dto 具有继承层次结构:
class Child1Dto : BaseDto {
class Child2Dto : BaseDto {
class Child3Dto : BaseDto {
...
我还有模型
BaseModel
class Child1Model : BaseModel {
class Child2Model : BaseModel {
class Child3Model : BaseModel {
现在我有以下代码:
fun BaseDto.toModel(): BaseModel =
when (this) {
is Child1Dto -> Child1Model(/*no args*/)
is Child2Dto -> Child2Model(/*no args*/)
is Child3Dto -> Child3Model(/*some args from dto*/)
else -> throw IllegalStateException("Unknown dto type ${this::class}")
}
我不喜欢这段代码,因为
有更好的方法重写这段代码吗?
您可以查看允许多态反序列化的@JsonSubTypes
例如,您可以定义一个父级:
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY, property = "fooProperty", visible = true)
@JsonSubTypes({
@JsonSubTypes.Type(value = ChildClassOne.class, name = "foo"),
@JsonSubTypes.Type(value = ChildClassTwo.class, name = "bar"),
@JsonSubTypes.Type(value = ChildClassThree.class, name = "baz")
}) public abstract class BaseDto { }
然后根据fooProperty
的值,将JSON反序列化到对应的子类中