Jackson은 Java 기반 라이브러리로, Java 객체를 JSON으로 변환하거나 JSON을 Java 객체로 변환할 때 유용하게 사용됩니다. Jackson 라이브러리에서는 @JsonFormat 어노테이션을 사용하여 여러 가지 날짜 형식을 매핑할 수 있습니다. 이 어노테이션은 속성 값이 직렬화되는 방식의 세부 사항을 설정하기 위한 범용 어노테이션입니다.
@JsonFormat의 주요 필드
@JsonFormat에는 세 가지 중요한 필드가 있습니다.
- shape: 직렬화에 사용할 구조를 정의합니다. (JsonFormat.Shape.NUMBER, JsonFormat.Shape.STRING)
- pattern: 직렬화 및 역직렬화 모두에 사용할 수 있습니다. 날짜의 경우 SimpleDateFormat과 호환되는 패턴 정의를 포함합니다.
- timezone: 직렬화 시 사용되며, 기본값은 시스템 기본 시간대입니다.
문법
@Target(value={ANNOTATION_TYPE,FIELD,METHOD,PARAMETER,TYPE})
@Retention(value=RUNTIME)
public @interface JsonFormat예제
아래 예제는 하나의 클래스 내에서 서로 다른 두 개의 날짜 형식을 @JsonFormat으로 각각 지정하여 역직렬화하는 방법을 보여줍니다.
import java.io.*;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonDateformatTest {
final static ObjectMapper mapper = new ObjectMapper();
public static void main(String[] args) throws Exception {
JacksonDateformatTest jacksonDateformat = new JacksonDateformatTest();
jacksonDateformat.dateformat();
}
public void dateformat() throws Exception {
String json = "{\"createDate\":\"1980-12-08\"," + "\"createDateGmt\":\"1980-12-08 3:00 PM GMT+1:00\"}";
Reader reader = new StringReader(json);
Employee employee = mapper.readValue(reader, Employee.class);
System.out.println(employee);
}
}
// Employee 클래스
class Employee implements Serializable {
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd", timezone = "IST")
private Date createDate;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm a z", timezone = "IST")
private Date createDateGmt;
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public Date getCreateDateGmt() {
return createDateGmt;
}
public void setCreateDateGmt(Date createDateGmt) {
this.createDateGmt = createDateGmt;
}
@Override
public String toString() {
return "Employee [\ncreateDate=" + createDate + ", \ncreateDateGmt=" + createDateGmt + "\n]";
}
}실행 결과
Employee [ createDate=Mon Dec 08 00:00:00 IST 1980, createDateGmt=Mon Dec 08 07:30:00 IST 1980 ]
결과 분석
위 실행 결과를 보면, createDate 필드는 yyyy-MM-dd 패턴으로 파싱되어 자정(00:00:00) 기준의 IST 시간대 날짜가 되었고, createDateGmt 필드는 시간과 시간대 정보(GMT+1:00)를 포함한 패턴으로 파싱되어 GMT+1 오후 3시가 IST 기준 오후 7시 30분으로 변환된 것을 확인할 수 있습니다.
이처럼 @JsonFormat 어노테이션을 활용하면 동일한 Date 타입이라도 필드별로 서로 다른 패턴과 시간대를 적용할 수 있어, 다양한 형식의 날짜 데이터를 유연하게 처리할 수 있습니다.