[JAVA] @JsonProperty, @JsonNaming

Yeri Kim·2024년 5월 13일

FE와 BE가 통신할 때, JSON을 통해서 통신하는 경우가 많다.
하지만, JSON에서는 Snake Case를 사용하고, Java에서는 Camel Case를 사용하기 때문에
이를 맞추어 JSON을 보내주어야한다.
스프링부트에는 이를 맞춰주는 @JsonProperty@JsonNaming 어노테이션이 존재한다.

예를 들어서,

public class Product {
    private int id;
    private int categoryId;
    private String name;
    private int price;
    private String descriptionTest;
}

이와 같은 DTO를 선언하고,

{
	"id" : 0,
  	"category_id" : 1,
	"name" : "notebook",
  	"price" : 1000,
  	"description_test" : "black"
}

이와 같은 RequestBody를 받는다면
categoryId <-> category_id
descriptionTest <-> description_test
변수 네이밍이 달라 데이터를 제대로 받을 수 없게 된다.

@JsonProperty

하나하나의 변수들을 네이밍할 수 있다.

private int id;
@JsonProperty("category_id")
private int categoryId;
private String name;
private int price;
@JsonProperty("description_test")
private String descriptionTest;

@JsonNaming

여러 개의 변수를 네이밍 해주어야할 때,
클래스에 적용하여 전체 멤버변수를 새로 네이밍 해줄 수 있다.

@JsonNaming(value = PropertyNamingStrategies.SnakeCaseStrategy.class)
public class Product {
    private int id;
    private int categoryId;
    private String name;
    private int price;
    private String descriptionTest;
}

참고한 블로그 :)

profile
Hi there!

0개의 댓글