Ignore a property in Dto from RequestBody base on endpoint (use one Dto for two purpose)

Viewed 867

I have a Coupon Table in the database so there are CouponEntity and CouponDto in the application. My question is about handling two endpoints with one Dto. for example, I have create and update endpoints, both of them use CouponDto. There is a business role that I can't update code property of the coupon entity. How to ignore it if the client passes this property in the request?

If I use @JsonIgnore, the property will be ignored in both the endpoints that I need to get it in create API. I used groups for validations and separate validations from each other, but @JsonIgnore can not be set sometimes.

For create a coupon:

@PostMapping("/create")
public ResponseEntity<?> createCoupon(@RequestBody CouponCodeDTO couponCodeDTO) {
    return ResponseEntity.ok(couponService.create(couponCodeDTO));
}

For update a coupon:

@PutMapping("/update/{id}")
public ResponseEntity<?> updateCoupon(
    @PathVariable Long id, @RequestBody CouponCodeDTO couponCodeDTO
) {
    return ResponseEntity.ok(couponService.update(id, couponCodeDTO));
}

And CouponDto:

public class CouponCodeDto extends BaseDto<Integer> {

    @NotBlank
    private String code;

    private Integer availableCount;

    @NotNull
    private LocalDate startDate;
    
   ...
}
1 Answers

You can use @JsonView to specify the field you want to serialize/deserialize per view and specify view on the endpoint.

public class Views {
    interface Update {}
    interface Create extends Update {}
}

public class CouponCodeDto extends BaseDto<Integer> {

    @NotBlank
    @JsonView(Views.Create.class)
    private String code;

    @JsonView(Views.Update.class)
    private Integer availableCount;

    @NotNull
    @JsonView(Views.Update.class)
    private LocalDate startDate;
    
   ...
}

And use on request body of the endpoint

@PutMapping("/update/{id}")
public ResponseEntity<?> updateCoupon(@PathVariable Long id, 
                   @JsonView(Views.Update.class) @RequestBody CouponCodeDTO couponCodeDTO) {

@PostMapping("/create")
public ResponseEntity<?> createCoupon(
                   @JsonView(Views.Create.class) @RequestBody CouponCodeDTO couponCodeDTO) {

Here you find details

https://www.baeldung.com/jackson-json-view-annotation

https://spring.io/blog/2014/12/02/latest-jackson-integration-improvements-in-spring

Related