본문 바로가기
Back-end/Java

[Java 에러] Get 통신에서 JsonProperty가 동작하지 않을 때

by whatamigonnabe 2022. 6. 30.

문제 상황

아래와 같이 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;
}