spring json 형태 반환 (SnakeCase or CamelCase)

최준호·2022년 11월 9일
0

업무

목록 보기
24/31
post-thumbnail

📗 json 형태 반환?

api 작업을 하다보면 데이터를 반환하는데 있어 SnakeCase 또는 CamelCase로 반환을 해주어야한다. 하지만 내 프로젝트에서는 CamelCase로 작업을 해놨는데 반환하거나 입력을 받을 때는 SnakeCase로 받아야할 때가 있다. 이러면 내 코드도 다 수정이 되어야하잖아!!! 이거는 너무 싫은 일이다. 그래서 Spring에서 자체적으로 제공해주는 기능이 있어서 정리해두려고 한다.

😍 역시 Jackson

Jackson library에서 제공하는 @JsonNaming@JsonProperty을 사용하여 입력이나 반환할 때 데이터를 조작하여 사용할 수 있게 해주는 어노테이션이 존재한다.

그럼 둘의 차이점과 사용법을 확인해보자.

✅ @JsonNaming

먼저 @JsonNaming은 class에 적용이 되는 어노테이션이다. 사용방법은

@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)
public class Dto {
	private String myUserName;
    private String myUserAge;
    private String myUserNickName;
}

다음과 같이 CamelCase로 작성된 네이밍 규칙을 SnakeCase로 모두 변경해주는 것이다.

변수로 들어가는 PropertyNamingStrategies의 코드를 살펴보면


    /**
     * Naming convention used in Java, where words other than first are capitalized
     * and no separator is used between words. Since this is the native Java naming convention,
     * naming strategy will not do any transformation between names in data (JSON) and
     * POJOS.
     *<p>
     * Example external property names would be "numberValue", "namingStrategy", "theDefiniteProof".
     */
    public static final PropertyNamingStrategy LOWER_CAMEL_CASE = new LowerCamelCaseStrategy();

    /**
     * Naming convention used in languages like Pascal, where all words are capitalized
     * and no separator is used between words.
     * See {@link UpperCamelCaseStrategy} for details.
     *<p>
     * Example external property names would be "NumberValue", "NamingStrategy", "TheDefiniteProof".
     */
    public static final PropertyNamingStrategy UPPER_CAMEL_CASE = new UpperCamelCaseStrategy();

    /**
     * Naming convention used in languages like C, where words are in lower-case
     * letters, separated by underscores.
     * See {@link SnakeCaseStrategy} for details.
     *<p>
     * Example external property names would be "number_value", "naming_strategy", "the_definite_proof".
     */
    public static final PropertyNamingStrategy SNAKE_CASE = new SnakeCaseStrategy();

    /**
     * Naming convention in which the words are in upper-case letters, separated by underscores.
     * See {@link UpperSnakeCaseStrategy} for details.
     * @since 2.13
     * <p>
     */
    public static final PropertyNamingStrategy UPPER_SNAKE_CASE = new UpperSnakeCaseStrategy();

    /**
     * Naming convention in which all words of the logical name are in lower case, and
     * no separator is used between words.
     * See {@link LowerCaseStrategy} for details.
     *<p>
     * Example external property names would be "numbervalue", "namingstrategy", "thedefiniteproof".
     */
    public static final PropertyNamingStrategy LOWER_CASE = new LowerCaseStrategy();

    /**
     * Naming convention used in languages like Lisp, where words are in lower-case
     * letters, separated by hyphens.
     * See {@link KebabCaseStrategy} for details.
     *<p>
     * Example external property names would be "number-value", "naming-strategy", "the-definite-proof".
     */
    public static final PropertyNamingStrategy KEBAB_CASE = new KebabCaseStrategy();

    /**
     * Naming convention widely used as configuration properties name, where words are in
     * lower-case letters, separated by dots.
     * See {@link LowerDotCaseStrategy} for details.
     *<p>
     * Example external property names would be "number.value", "naming.strategy", "the.definite.proof".
     */
    public static final PropertyNamingStrategy LOWER_DOT_CASE = new LowerDotCaseStrategy();

네이밍 규칙에 사용되는 여러 규칙들을 미리 정의해둔 것을 확인해 볼 수 있다.

✅ @JsonProperty

@JsonProperty는 class 범위가 아닌 변수에 적용시킬 수 있는 것인데

public class EmailSignupResponse {
    @JsonProperty("member_seq")
    private Long memberSeq;
    private String token;
    ...
}

다음과 같이 하나의 변수에만 값이 변경되어야할 경우에는 @JsonProperty을 사용하여 데이터의 값을 변경시켜줄 수 있다.

profile
코딩을 깔끔하게 하고 싶어하는 초보 개발자 (편하게 글을 쓰기위해 반말체를 사용하고 있습니다! 양해 부탁드려요!) 현재 KakaoVX 근무중입니다!

0개의 댓글