Java JSON 처리 실전 시리즈 2화 – Spring Boot에서 Jackson 기본 설정 이해하기
Spring Boot에서 Jackson은 기본 JSON 파서로 작동합니다. 날짜 포맷, null 필드 처리, 네이밍 전략까지 설정 파일과 Java Config를 활용한 커스터마이징 방법을 소개합니다.
Spring Boot 기반 웹 애플리케이션을 만들면 @RestController에서 객체를 반환할 때 자동으로 JSON으로 변환되는 것을 볼 수 있습니다.
이 모든 처리는 Jackson의 ObjectMapper와 Spring Boot의 HTTP Message Converter 덕분입니다.
이번 글에서는 Spring Boot가 Jackson을 어떻게 통합하고 있는지, 그리고 우리가 어떤 설정을 통해 JSON 출력을 제어할 수 있는지를 다룹니다.
1. Jackson과 Spring Boot의 통합 구조
Spring Boot 2.0 이상에서는 Jackson이 자동으로 다음 구성에 따라 통합됩니다:
- MappingJackson2HttpMessageConverter를 통해 HTTP 응답을 JSON으로 변환
- 내부적으로 ObjectMapper 인스턴스를 Bean으로 등록하고 관리
- application.yml 또는 application.properties로 Jackson 설정 가능
이 덕분에 별도 설정 없이도 다음과 같이 객체를 반환하면 자동으로 JSON 응답이 생성됩니다:
@RestController
public class UserController {
@GetMapping("/user")
public User getUser() {
return new User("홍길동", 30);
}
}
2. application.yml로 Jackson 설정하기
Spring Boot는 다양한 Jackson 설정을 application.yml에서 직접 지정할 수 있습니다. 예시:
spring:
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: Asia/Seoul
serialization:
indent-output: true
deserialization:
fail-on-unknown-properties: false
property-naming-strategy: SNAKE_CASE
default-property-inclusion: non_null
주요 설정 항목
항목 설명
date-format | 날짜 형식 지정 (@JsonFormat보다 우선 적용) |
time-zone | 시간대 설정 |
indent-output | JSON 출력 시 들여쓰기 활성화 |
fail-on-unknown-properties | 매핑되지 않은 필드 무시 여부 |
property-naming-strategy | Camel ↔ Snake 자동 변환 |
default-property-inclusion | null 필드 포함 여부 (non_null, non_empty) |
3. Java Config에서 ObjectMapper 직접 설정하기
설정을 더 세밀하게 제어하고 싶다면, ObjectMapper를 직접 커스터마이징하는 Bean을 정의할 수 있습니다:
@Configuration
public class JacksonConfig {
@Bean
public ObjectMapper objectMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE);
return mapper;
}
}
단, Spring Boot에서 자동 등록한 ObjectMapper를 대체하게 되므로, 의존성 설정이 꼬이지 않도록 주의해야 합니다.
4. 컨트롤러 출력 포맷 예제
public class User {
private String userName;
private LocalDateTime createdAt;
// getter/setter 생략
}
위 클래스에 대해 다음 설정을 적용하면:
spring:
jackson:
property-naming-strategy: SNAKE_CASE
date-format: yyyy-MM-dd HH:mm:ss
응답 결과는 다음과 같이 출력됩니다:
{
"user_name": "홍길동",
"created_at": "2025-05-09 10:30:00"
}
5. 테스트에서 ObjectMapper 활용하기
Spring Boot Test에서 JSON 응답을 검증하거나 직접 변환할 때도 ObjectMapper를 쉽게 사용할 수 있습니다:
@Autowired
private ObjectMapper objectMapper;
@Test
void testJsonSerialization() throws Exception {
User user = new User("홍길동", 30);
String json = objectMapper.writeValueAsString(user);
System.out.println(json);
}
결론 및 팁 요약
- Jackson은 Spring Boot의 기본 JSON 변환기입니다.
- application.yml만으로도 상당수의 JSON 포맷 커스터마이징이 가능합니다.
- 날짜 포맷, null 필드, 네이밍 전략을 미리 설정해두면 컨트롤러 코드가 훨씬 깔끔해집니다.
- 필요 시 ObjectMapper를 직접 Bean으로 등록해 상세 제어도 가능합니다.
다음 회차 예고
3화에서는 ObjectMapper의 기본 동작과 함께, @JsonProperty, @JsonIgnore, @JsonInclude와 같은 Jackson 어노테이션을 활용한 객체 → JSON 변환 전략을 실습 위주로 정리합니다.