Files
java-examples/docs/Jackson.md

4.8 KiB

Jackson 어노테이션 정리 및 예제

1. Jackson이란?

Jackson자바 객체를 JSON으로 변환하거나 JSON을 자바 객체로 변환하는 라이브러리다.
Spring Boot에서도 기본적으로 사용되며, 속도가 빠르고 사용법이 간단하다.

Jackson의 주요 기능자바 객체 → JSON 변환 (ObjectMapper.writeValue())
JSON → 자바 객체 변환 (ObjectMapper.readValue())
JSON 포맷 커스터마이징 (필드 제외, 포맷 변경 등)


2. Jackson 주요 어노테이션 정리

📌 직렬화 (객체 → JSON) 관련 어노테이션

어노테이션 설명
@JsonProperty 필드의 JSON 속성명을 변경
@JsonIgnore 특정 필드를 JSON 변환에서 제외
@JsonIgnoreProperties 여러 필드를 JSON 변환에서 제외
@JsonInclude null 값 또는 기본값을 JSON에서 제외
@JsonGetter getter 메서드의 JSON 속성명을 변경

📌 역직렬화 (JSON → 객체) 관련 어노테이션

어노테이션 설명
@JsonCreator JSON 데이터를 객체로 변환할 때 생성자 지정
@JsonSetter setter 메서드의 JSON 속성명을 변경
@JsonAlias 여러 개의 JSON 키를 하나의 필드로 매핑
@JsonIgnoreProperties(ignoreUnknown = true) JSON에 없는 필드 무시

📌 날짜/시간 관련 어노테이션

어노테이션 설명
@JsonFormat 날짜/시간 포맷을 지정
@JsonDeserialize 커스텀 역직렬화 지정
@JsonSerialize 커스텀 직렬화 지정

📌 고급 기능 관련 어노테이션

어노테이션 설명
@JsonUnwrapped 중첩 객체의 필드를 부모 객체에 포함
@JsonTypeInfo 다형성(Polymorphism) 처리를 위한 타입 정보 추가

3. Jackson 어노테이션 예제

✔ 1) @JsonProperty - JSON 속성명 변경

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;

class User {
    @JsonProperty("full_name")
    private String name;
    
    private int age;

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    // Getter & Setter 생략
}

public class JacksonExample {
    public static void main(String[] args) throws Exception {
        ObjectMapper objectMapper = new ObjectMapper();
        User user = new User("홍길동", 30);
        
        String json = objectMapper.writeValueAsString(user);
        System.out.println(json);  // 출력: {"full_name":"홍길동","age":30}
    }
}

필드명이 name이지만, JSON에서는 full_name으로 출력됨!


✔ 2) @JsonIgnore - 특정 필드 제외

import com.fasterxml.jackson.annotation.JsonIgnore;

class User {
    private String name;
    
    @JsonIgnore
    private String password; // JSON에서 제외됨

    public User(String name, String password) {
        this.name = name;
        this.password = password;
    }
}

🔹 변환 결과

{"name":"홍길동"}

password 필드는 JSON에서 제외됨!


✔ 3) @JsonInclude - null 값 제외

import com.fasterxml.jackson.annotation.JsonInclude;

@JsonInclude(JsonInclude.Include.NON_NULL)
class User {
    private String name;
    private String nickname; // null 값일 경우 JSON에서 제외됨

    public User(String name, String nickname) {
        this.name = name;
        this.nickname = nickname;
    }
}

🔹 변환 결과 (nicknamenull일 때)

{"name":"홍길동"}

nicknamenull이면 JSON에서 제외됨!


✔ 4) @JsonAlias - 여러 개의 키를 하나의 필드로 매핑

import com.fasterxml.jackson.annotation.JsonAlias;

class User {
    @JsonAlias({"full_name", "user_name"})
    private String name;
}

JSON의 "full_name" 또는 "user_name"이 모두 name 필드로 매핑됨!


✔ 5) @JsonFormat - 날짜 포맷 변경

import com.fasterxml.jackson.annotation.JsonFormat;
import java.util.Date;

class Event {
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
    private Date eventDate;
}

날짜를 "2025-03-06 14:30:00" 형식으로 변환 가능!


4. Jackson 정리

Jackson은 JSON 변환을 위한 강력한 라이브러리
어노테이션을 활용하면 JSON 변환을 세밀하게 제어 가능
필드명 변경, 필드 제외, 날짜 포맷 지정 등 다양한 기능 지원

Jackson을 사용하면 JSON 변환이 훨씬 쉽고 간결해짐!