문제 상황
아래와 같이 Get으로 통신을 할 때, DTO객체를 사용하려고 합니다.
그런데 DTO의 멤버 변수 이름이 Camel case로 되어 있고 client의 요청은 Snake case로 온다고 했을 때,
@JsonProperty 어노테이션이나 @JsonNaming 어노테이션을 사용해서 자동으로 바꿔주려고 하는데,
이상하게 계속 제대로 인식되지 않고 아래처럼 null이 반환되고 있습니다.
//controller class
@GetMapping("/simple")
public UserDto simpleTest(UserDto userDto) {
return userDto;
}
//DTO 클래스
public class UserDto {
@JsonProperty("user_name")
private String userName;
@JsonProperty("phone_number")
private String phoneNumber;
}


원인
결론적으로 원인은 위의 두 개의 어노테이션은 Post나 Put 등 body에 정보를 담아서 request를 할 때 key값을 맞춰주는 것에 쓰이고,
위 처럼 쿼리 파라미터의 키값에는 적용이 되지 않는다.
해결방안
1. Post method를 통해 통신하기
쿼리 파라미터에 담았던 정보를 body에 담아서 요청하면 정상적으로 작동한다.
2. @ConstructorProperties 사용
DTO클래스에서 @ConstructorProperties어노테이션을 쓰면 원하는 결과를 얻을 수 있다.
//DTO class 내의 생성자
@ConstructorProperties({"user_name", "phone_number"})
public UserDto(String userName, String phoneNumber) {
this.userName = userName;
this.phoneNumber = phoneNumber;
}

'Back-end > Java' 카테고리의 다른 글
| Java의 Functional Interface (0) | 2023.04.27 |
|---|---|
| [JAVA] 불필요한 객채 생성을 막자. 싱글톤 패턴과 정적 초기화 블럭 (0) | 2022.07.09 |
| [JAVA] 내부 클래스 간단 정리와 사용 이유 (0) | 2022.07.08 |