gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 09:48:06 29 4
gpt4 key购买 nike

我尝试从方法响应正文中获取派生类字段。请求体参数是基类的类型。请求带有派生类字段,但我无法将其转换为派生类。

这是我的 Controller 方法和 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 ?

最佳答案

使用Jackson inheritance特征。将 PromotionDto 类注释如下:

@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.PROPERTY,
property = "promotionType")
@JsonSubTypes({
@Type(value = OrderThresholdDiscountPromotionDto.class, name = "ORDER_THRESHOLD_DISCOUNT"),
})
class PromotionDto {

并删除:

private PromotionTypeEnum promotionType;

属性(property)。它将由 Jackson 自动处理。在 Controller 中,您将能够使用 instanceof

关于java - 从基类请求主体 DTO 获取派生 DTO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55161374/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com