有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java从基类请求体DTO获取派生DTO

我试图从方法响应体中获取派生类字段。请求主体参数是基类的类型。请求带有派生类字段,但我不能将其强制转换为派生类

以下是我的控制器方法和DTO类:

方法:

 @PostMapping("/{code}")
    public ResponseEntity<PromotionDto> createPromotion(@PathVariable String code, @RequestBody PromotionDto promotion){
        if(PromotionTypeEnum.ORDER_THRESHOLD_DISCOUNT.equals(promotion.getPromotionType())) {
            promotionService.createPromotion(orderThresholdDiscountPromotionConverter.toEntity((OrderThresholdDiscountPromotionDto)promotion));
        }
        return ResponseEntity.ok(promotion);
    }

基类DTO:

import dto.base.BaseDto;
import promotionservice.PromotionTypeEnum;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;

@Data
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
public class PromotionDto extends BaseDto {
    private String code;
    private String title;
    private String description;
    private PromotionTypeEnum promotionType;

}

派生类DTO:

import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;

@Data
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
public class OrderThresholdDiscountPromotionDto extends PromotionDto {
    private Double thresholdTotal;
    private Double discountPrice;
    private String messageFired;
    private String messageCouldHaveFired;
}

请求JSON是:

{
    "code":"qwewe",
    "title":"qwewe",
    "description":"qwewe",
    "promotionType":"ORDER_THRESHOLD_DISCOUNT",
    "thresholdTotal":1.3,
    "discountPrice":"12.5",
    "messageFired":"qwewe",
    "messageCouldHaveFired":"qwewe"

}

因此,服务返回错误:

{
"type": "https://www.jhipster.tech/problem/problem-with-message",
"title": "Internal Server Error",
"status": 500,
"detail": "promotion.PromotionDto cannot be cast to promotion.OrderThresholdDiscountPromotionDto",
"path": "/api/promotionresults/qwewe",
"message": "error.http.500"

}

My question is: is there any way, library, annotation etc. to get the derived class instance from request ?


共 (0) 个答案