티스토리 뷰

 

 

 

API를 설계하다 보면 서버에서 요청 값으로 설계한 Request DTO의 네이밍과 클라이언트 쪽에서 요청하는 Json 네이밍이 간혹 다른 경우가 발생합니다. 이런 경우에 Json 데이터를 DTO 객체에 매핑하는 과정에서 key값이 일치하지 않아 매핑되지 않는 문제가 발생하게 되는데요. 이때 @JsonProperty, @JsonNaming 어노테이션을 사용하면 문제를 해결할 수 있습니다.

 

 

@JsonProperty


아래는 서버에서는 카멜케이스를 사용하지만 클라이언트 쪽에서는 언더바를 이용하여 요청을 한 코드이다.

//Json 요청 예시
{ 
    "post_name": "nori",
    "post_content": "zzang",
    "category": "FREE"
}
@Data
public class WriteRequest {

    @JsonProperty("post_name") // Json으로 요청된 값
    private String postName;

    @JsonProperty("post_content") // Json으로 요청된 값
    private String postContent;

    private String category;

}

위 처럼 변경하고자 하는 필드에 각각 @JsonProperty를 붙여주면 된다.

그런데 만약 필드가 30개 이상 된다면 유지보수에도 어렵고, 코드 가독성에도 좋지 않다.

이럴 때 사용하는 것이 @JsonNaming이다.

 

 

@JsonNaming


//Json 요청 예시
{ 
    "post_name": "nori",
    "post_content": "zzang",
    "category": "FREE"
}
@Data
@JsonNaming(value = PropertyNamingStrategy.SnakeCaseStrategy.class)
public class WriteRequest {

    private String postName;

    private String postContent;

    private String category;

}

@JsonNaming 어노테이션을 클래스단에 붙여주고, 사용하고자 하는 전략을 명시해주면 모든 필드에 적용이 가능하다.

 

 

 

 

참고

https://cbw1030.tistory.com/315

 

'Spring' 카테고리의 다른 글

[Spring] Spring Initializr 사용 방법  (0) 2021.12.14
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
글 보관함