Search code examples
jsonspringspring-bootpostmanjson-framework

Null values for both @RequestBody Objects sent with PUT method on Postman to RestController?


I want to send two different Objects via PUT method, first Object is UserDTO and second is AdsDTO. But fore some reason they both are null in service implementation. This is my json:

{

 "userDTO" :
  {
  "aboutUs": "xxx",
  "address": "xxx",
  "businessType": "xxx",
  "city": "xx",
  "company": "xxxx",
  "companyImage": [
    "xxx","xxx"
  ],
  "credit": "xx",
  "dateOfBirth": "xxx",
  "email": "xxx",
  "location": "xxx",
  "mobile": "xxx",
  "name": "xxx",
  "phone": "xxx",
  "region": "xxx",
  "roleName": "xxx",
  "surname": "xxx",
  "userName": "xxx",
  "visible": "xxx",
  "website": "xxx"
}, 
"adsDTO" : {
  "adsGroupId": "xx",
  "adsSubGroupId": "xx",
  "adsType": "xxx",
  "description": "xxx",
  "image": [
    "xxx", "xxx"
  ],
  "price": "xxx",
  "productName": "xxx"}
}

And my controler:

@PutMapping("users/favourites")
    public ResponseEntity<UserDTO> updateUserFavourites(@RequestHeader("Authorization")String token, @RequestBody UserDTO userDTO, AdsDTO adsDTO) throws NotFoundException, ForbiddenException, BadRequestException{
        
        return new ResponseEntity<UserDTO>(jwtUserServiceImplement.updateUserFavourites(userDTO, token, adsDTO), HttpStatus.OK);
    }

Of course, this xxx are hidden values :) . And when I hit PUT request on Postman and debug app I see that both of my @RequestBody params are null. Just to say that I saw some similar problems,and one of possible solutions was missing getters/settters but I have them. Maybe this error is because of my controller, but I am pretty sure that error is because bad JSON formatting. Can someone help me?


Solution

  • You can't have two objects for @RequestBody. But you can create a request object which encapsulates your two DTOs and use that:

    public class UserAdsRequest {
        private userDTO;
        private adsDTO;
    
        // getters and setters
    }
    
        PutMapping("users/favourites")
        public ResponseEntity<UserDTO> updateUserFavourites(@RequestHeader("Authorization")String token, @RequestBody UserAdsRequest userAdsRequest) throws NotFoundException, ForbiddenException, BadRequestException{
    
            return new ResponseEntity<UserDTO>(jwtUserServiceImplement.updateUserFavourites(userAdsRequest.getUserDTO(), token, userAdsRequest.getAdsDTO()), HttpStatus.OK);
        }