[SpringBoot] Jackson 어노테이션 (1)

해니·2023년 12월 18일
0

SpringBoot

목록 보기
8/24
post-thumbnail

@JsonCreator

  • Json 데이터를 Java 객체로 받고 싶은 경우 사용한다.
  • Constructor(생성자) 위에 어노테이션을 추가하여 사용한다.
  • 파라미터에 @JsonProperty를 사용하여 json key값을 명시한다.
    • json key값과 Java 객체의 프로퍼티가 같다면 생략 가능하다.

{
  "code": "TEST1",
  "description": "테스트 코드입니다."
}
@Getter
@ToString
public class CodeDto {

    private String code;
    private String description;

    @JsonCreator
    public JsonCreatorDTO(@JsonProperty("code") String code, @JsonProperty("description") String description) {
        this.code = code;
        this.description = description;
    }
}



@JsonValue

  • getter@JsonValue 해당 멤버 필드가 이름을 통해 직렬화 시킨다.
  • Enum 사용 시, 특정 값만 리턴하고 싶다면, 변수에 @JsonValue 어노테이션을 추가해준다.

public enum EnumWithValue {

    ENUM1(1, "TYPE1"),
    ENUM2(2, "TYPE2");

    private Integer intValue;
    private String strValue;

    private EnumWithValue(Integer intValue, String strValue) {
        this.intValue = intValue;
        this.strValue = strValue;
    }

    @JsonValue
    public Integer getIntValue() {
        return intValue;
    }

    public String getStrValue() {
        return strValue;
    }
}
@AllArgsConstructor
@Getter
public enum Foo {

  A("에이", "a"),
  B("비", "b"),
  C("씨", "c");

  @JsonValue
  private String korean;
  private String small;

}



@JsonFormat

  • LocalDate / LocalDateTime 을 JSON으로 직렬화 할때 포맷을 관리한다.
    • Post요청시 RequestBodyReponseBody에서 사용한다.
  • Enum 사용 시, 객체 전체 리턴을 원하는 경우, @JsonFormat 어노테이션을 추가해준다.
    • 리턴받는 기댓값은 객체 형태이기 때문에 Shape.OBJECT로 설정해준다.

@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime startDay;
@JsonFormat(shape = Shape.OBJECT)
@AllArgsConstructor
@Getter
public enum Foo {

  A("에이", "a"),
  B("비", "b"),
  C("씨", "c");

  private String korean;
  private String small;

}



@JsonIgnore

  • 직렬화 시 해당 필드를 포함시키고 싶지 않을 때 선언하는 어노테이션
  • 해당 어노테이션을 사용하면 Response 데이터에서 해당 필드가 제외된다.

    @JsonIgnore
    private Map<String, Object> tmpData;






출처
Jackson Deserialization Annotation
Spring Boot - 직렬화!
Jackson의 모든 것 - 역 직렬화 편
Jackson의 모든 것 - 직렬화 편
@JsonIgnore 이란?
[JAVA] Spring Boot json Enum json object or jsonvalue
[Spring Boot] json response할 때 Enum 객체 전체 보여주기
[Spring boot] 날짜 타입 JSON 변환

profile
💻 ⚾️ 🐻

0개의 댓글