IT/Java
[Java] Jackson으로 Json 변환 시, 날짜 포맷 적용하기(DateFormat)
hi.anna
2021. 9. 5. 12:56
Jackson 라이브러리를 사용하여
Java Object를 Json 문자열로 변환할 때
Date 객체의 포맷을 지정할 수 있습니다.
Date 객체를 Json으로 변환하기 (Format 지정하기)
import java.text.SimpleDateFormat;
import java.util.Date;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonDate1 {
public static void main(String[] args) throws JsonProcessingException {
// Lecture 객체 생성
Lecture lecture = new Lecture();
lecture.setName("Java");
lecture.setDate(new Date());
// Date Format 없이 Json변환
dateToJson(lecture);
// Date Format 지정하여 Json 변환
dateToJsonWithDateFormat(lecture);
}
public static void dateToJson(Lecture lecture) throws JsonProcessingException {
// jackson objectmapper 객체 생성
ObjectMapper objectMapper = new ObjectMapper();
// Lecture 객체 -> Json 문자열
String studentJson = objectMapper.writeValueAsString(lecture);
// Json 문자열 출력
System.out.println(studentJson); // {"name":"Java","date":1630813646681}
}
public static void dateToJsonWithDateFormat(Lecture lecture) throws JsonProcessingException {
// jackson objectmapper 객체 생성
ObjectMapper objectMapper = new ObjectMapper();
// Date Format 설정
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
objectMapper.setDateFormat(dateFormat);
// Lecture 객체 -> Json 문자열
String studentJson = objectMapper.writeValueAsString(lecture);
// Json 문자열 출력
System.out.println(studentJson); // {"name":"Java","date":"2021-09-05"}
}
}
위 예제는 Date 항목을 가지는 객체를 Json으로 변환할 때,
Format을 지정하지 않았을 때와
Format을 지정하여 변환하는 방법을 보여주는 예제입니다.
dateToJson()
date format을 지정하지 않고,
객체를 Json으로 변환하였습니다.
이 경우, Date 객체는 Json으로 변환될때 날짜를 나타내는 숫자로 변환됩니다.
dateToJsonWithDateFormat()
ObjectMapper에 setDateFormat() 메소드를 이용하여
날짜 포맷을 지정하였습니다.
지정된 날짜 포맷으로 Json이 생성됩니다.
Jackson 라이브러리를 사용하여 Json 문자열을 생성할 때
Date 객체를 처리하는 방법을 알아보았습니다.
반응형