繁体   English   中英

如何在控制器中使用@RequestBody 将值映射到 DTO 时忽略 @JsonProperty 值

[英]How to ignore the @JsonProperty value while using the @RequestBody in controller to map value to DTO

我想根据变量名称而不是 @JsonProperty 值将我的 HTTP 请求参数值直接映射到我的 DTO 使用 @JsonProperty。 我无法将该值映射到 DTO,因为它根据 JsonProperty 名称期待请求值。 无论如何在使用 @RequestBody 时禁用 @JsonProperty 值?

前端发送的 JSON:

{
"userId":"1",
"payMethod":"payMethod"
}

MyDto.class 公共类 MyDto{

    @JsonProperty(value = user_id, required = true)
    private String userId;


    @JsonProperty(value = BETAALMETHODE, required = true)
    private String payMethod;
//getter setter
   }

我的控制器类

public class MyController{

  @RequestMapping(value = "payment", method = RequestMethod.PUT)
    public Integer PaymentUpdate(@RequestBody final MyDto myDto) throws JsonProcessingException {

}

您可以通过对该 DTO 方法使用多个 setter 方法来做到这一点。 例如

Payload:
{
"userId":"1",
"payMethod":"payMethod"
}

然后

MyDto.class 公共类 MyDto{

@JsonProperty(value = user_id, required = true)
    private String userId;


    @JsonProperty(value = BETAALMETHODE, required = true)
    private String payMethod;

在 DTO 类中添加一个与所需变量名称相关的 setter。

@JsonSetter("specifiedName")
void setUserId(String userId){
     this.userId=userId
}

void setPayMethod(String payMethod){ // Will work for "BETAALMETHODE" variable name
     this.payMethod=payMethod
}
@JsonSetter("payMethod")
void setPayMethod(String payMethod){
     this.payMethod=payMethod
}

这将解决您的问题,变量 payMethod 将在这两种情况下分配。

您可以在 csv 解析过程中使用JacksonMixin

public abstract class MyDtoMixin {
    @JsonProperty(value = user_id, required = true)
    private String userId;

    @JsonProperty(value = BETAALMETHODE, required = true)
    private String payMethod;
}


ObjectMapper mapper = new ObjectMapper(); // or CsvMapper mapper = new CsvMapper();
mapper.addMixInAnnotations(MyDto.class, MyDtoMixin.class);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM