Jackson 직·역직렬화 어노테이션 핵심(@Json*)
Jackson은 스프링에서 기본 JSON 바인더로 가장 널리 쓰입니다. 핵심 어노테이션만 정확히 알면, DTO·레코드·다형성 모델을 안전하게 매핑할 수 있습니다.
필드명 매핑과 생성자 바인딩
public record SignUp(
@JsonProperty("email") String email,
@JsonProperty("password") String password
) {}
public class Amount {
private final int value;
@JsonCreator
public Amount(@JsonProperty("value") int value) { this.value = value; }
public int getValue() { return value; }
}
무시/포함 규칙 & 널 전략
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Profile {
public String name;
@JsonIgnore public String secret; // JSON 출력 제외
}
날짜/시간 포맷
public record Event(
String name,
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ssXXX")
OffsetDateTime at
) {}
커스텀 직·역직렬화
public class MoneySerializer extends JsonSerializer<Money> {
@Override public void serialize(Money m, JsonGenerator g, SerializerProvider s) throws IOException {
g.writeString(m.amount()+" "+m.currency());
}
}
public class MoneyDeserializer extends JsonDeserializer<Money> {
@Override public Money deserialize(JsonParser p, DeserializationContext c) throws IOException {
String[] t = p.getValueAsString().split(" ");
return new Money(Long.parseLong(t[0]), t[1]);
}
}
@JsonSerialize(using = MoneySerializer.class)
@JsonDeserialize(using = MoneyDeserializer.class)
public record Money(long amount, String currency) {}
다형성(폴리모픽) 타입
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes({
@JsonSubTypes.Type(value = Card.class, name = "card"),
@JsonSubTypes.Type(value = Bank.class, name = "bank")
})
sealed interface Payment permits Card, Bank {}
record Card(String number) implements Payment {}
record Bank(String account) implements Payment {}
자주 하는 실수
- 필수 필드 누락: 생성자/레코드에
@JsonProperty잊지 않기 - 순환참조:
@JsonManagedReference/@JsonBackReference또는@JsonIdentityInfo검토 - Lombok와 혼용:
@Builder사용 시 필수 검증은 생성자에서 처리
👉 1편: Dockerfile 멀티스테이지로 이미지 절반 만들기
👉 2편: GitHub Actions: push 시 테스트 자동화 YAML
'Java & Spring' 카테고리의 다른 글
| Spring Security 6: JWT 로그인/리프레시 토큰 (0) | 2025.10.08 |
|---|---|
| springdoc-openapi로 API 문서 1분 셋업 (0) | 2025.10.05 |
| 페이징 성능: 카운트 최적화·키셋 페이징 (0) | 2025.10.03 |
| @Transactional 전파/고립수준 이해 (1) | 2025.10.03 |
| 메서드명 쿼리 vs @Query vs QueryDSL 비교 (0) | 2025.10.02 |