사용자 도구

사이트 도구


springframework:springboot:json

차이

문서의 선택한 두 판 사이의 차이를 보여줍니다.

차이 보기로 링크

양쪽 이전 판 이전 판
다음 판
이전 판
springframework:springboot:json [2018/11/27 15:12]
kwon37xi [모든 타입에 대해 일관성 있는 커스텀 형식 지원]
springframework:springboot:json [2020/11/23 19:00] (현재)
kwon37xi [WRITE_DATES_AS_TIMESTAMPS=false 사용]
줄 7: 줄 7:
  
 ==== 기본 설정 ==== ==== 기본 설정 ====
-  * 의존성에 다음 추가해야 JSR310 날짜/시간 지원됨.<code groovy>+  * SpringBoot 2.x 는 starter 추가 하면 Jackson ''ObjectMapper'' 자동 생성 설정<code groovy> 
 +api 'org.springframework.boot:spring-boot-starter-json' 
 +</code> 
 +  * 구버전 SpringBoot 에서는 의존성에 다음 추가해야 JSR310 날짜/시간 지원됨.<code groovy>
 compile('com.fasterxml.jackson.datatype:jackson-datatype-jsr310') compile('com.fasterxml.jackson.datatype:jackson-datatype-jsr310')
 compile('com.fasterxml.jackson.datatype:jackson-datatype-jdk8') compile('com.fasterxml.jackson.datatype:jackson-datatype-jdk8')
줄 37: 줄 40:
 } }
 </code> </code>
 +
 ==== WRITE_DATES_AS_TIMESTAMPS=false 사용 ==== ==== WRITE_DATES_AS_TIMESTAMPS=false 사용 ====
   * 제일 좋은 것은 처음부터 ''WRITE_DATES_AS_TIMESTAMPS=false'' 상태로 운영하는 것이다. ''application.yml''<code>   * 제일 좋은 것은 처음부터 ''WRITE_DATES_AS_TIMESTAMPS=false'' 상태로 운영하는 것이다. ''application.yml''<code>
 spring.jackson.serialization.write-dates-as-timestamps: false spring.jackson.serialization.write-dates-as-timestamps: false
 </code> </code>
-  * SpringBoot 2.x 는 이값이 **기본 ''false''** 이로 ISO 포맷을 사용할 경우에는 ''simpleDateFormat''만 따로 ISO와 동일하게 설정해주면 된다.+  * SpringBoot 2.x 는 이값이 **기본 ''false''** 이고 Java 8 date/time 에 대해 자동으로 ISO 포맷을 사용하게 한다. ''simpleDateFormat''만 따로 ISO와 동일하게 설정해주면 된다
 +    * **''simpleDateFormat(), dateFormat()''을 설정하면 ''ObjectMapper''가 non-thread-safe 하게 돼 버린다.** 하지말고, ''java.util.Date''도 사용하지 말 것.
   * 이렇게 하면 ''java.util.Date'',''java.time.*'' 모두 ISO 혹은 그 유사 포맷으로 직렬화된다.<code>   * 이렇게 하면 ''java.util.Date'',''java.time.*'' 모두 ISO 혹은 그 유사 포맷으로 직렬화된다.<code>
 {   {  
줄 53: 줄 58:
 </code> </code>
   * 그러나 ''WRITE_DATES_AS_TIMESTAMPS'' 옵션을 변경할 경우 기존에 작동하던 ''java.util.Date''의 포맷이 변경되므로 프로젝트가 이미 운영중일 때는 ''java.util.Date''를 받는 모든 부분에 대해 기존 unix timestamp 받던것을 올바로 처리하게 변경해야만 한다.   * 그러나 ''WRITE_DATES_AS_TIMESTAMPS'' 옵션을 변경할 경우 기존에 작동하던 ''java.util.Date''의 포맷이 변경되므로 프로젝트가 이미 운영중일 때는 ''java.util.Date''를 받는 모든 부분에 대해 기존 unix timestamp 받던것을 올바로 처리하게 변경해야만 한다.
 +  * Formatter와 Jackson Serializers/Deserializers 에 대해서 테스트를 만들어 보증하는 것이 좋다. [[https://gist.github.com/kwon37xi/aa359e364b7e81f79085fb04cc710037|FormatterSerializerTestControllerTest.groovy]]
  
 ==== 모든 타입에 대해 일관성 있는 커스텀 형식 지원 ==== ==== 모든 타입에 대해 일관성 있는 커스텀 형식 지원 ====
줄 113: 줄 119:
 }</code> }</code>
   * ''DateTimeForamtter.ISO_ZONED_DATE_TIME''은 표준이 아니다. jackson은 ''ZonedDateTime''에 대해 기본으로 ''ISO_OFF_SET_DATE_TIME''을 사용한다.   * ''DateTimeForamtter.ISO_ZONED_DATE_TIME''은 표준이 아니다. jackson은 ''ZonedDateTime''에 대해 기본으로 ''ISO_OFF_SET_DATE_TIME''을 사용한다.
 +
 +==== Jackson2ObjectMapperBuilder 사용시 Module 추가 ====
 +  * ''Jackson2ObjectMapperBuilder'' 사용시 모듈을 추가하려면 ''modules'' 메소드 혹은 ''modulesToInstall''를 사용한다.
 +  * ''modules(...)'' : Spring과 Jackson default 모듈 탐색을 모두 취소하고 오직 이 메소드 인자로 전달된 모듈만 탑재
 +  * ''modulesToInstall(...)'' : Spring(JSR-310 or jodatime 등 자동추가)과 Jackson default 모듈 탑재를 수행하고 그 뒤에 명시된 모듈을 추가 탑재
 ==== @EnableWebMvc ==== ==== @EnableWebMvc ====
 ''@EnableWebMvc''와 ''WebMvcConfigurerAdapter''를 사용하는 순간 더이상 SpringBoot가 아니고 Spring 이기 때문에 위의 설정이 먹지 않게 된다. [[springframework:springboot:mvc|SpringBoot and Spring MVC]] 참조 [[https://github.com/spring-projects/spring-boot/issues/2116|Spring Boot Issue 2116]] ''@EnableWebMvc''와 ''WebMvcConfigurerAdapter''를 사용하는 순간 더이상 SpringBoot가 아니고 Spring 이기 때문에 위의 설정이 먹지 않게 된다. [[springframework:springboot:mvc|SpringBoot and Spring MVC]] 참조 [[https://github.com/spring-projects/spring-boot/issues/2116|Spring Boot Issue 2116]]
줄 146: 줄 157:
 } }
 // 파라미터를 ?datetime=2018-07-11T20:22:55.123 형태로 호출 // 파라미터를 ?datetime=2018-07-11T20:22:55.123 형태로 호출
 +</code>
 +
 +==== @JsonComponent ====
 +  * [[https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/jackson/JsonComponent.html|@JsonComponent]] 애노테이션을 통해서 Serializer와 Deserializer를 bean으로 등록하면 자동으로 Jackson ObjectMapper에 해당 컴포넌트를 Serializer와 Deserializer로 등록해준다.
 +  * [[https://www.baeldung.com/spring-boot-jsoncomponent|Using @JsonComponent in Spring Boot | Baeldung]]
 +
 +==== WebFlux Jackson 설정 ====
 +  * [[springframework:webflux|Spring WebFlux]] Jackson 설정
 +  * ''@EnableWebFlux''는 SpringBoot에서는 해서는 안 된다.
 +  * https://stackoverflow.com/a/43241547/1051402
 +
 +<code java>
 +@Configuration
 +public class Config implements WebFluxConfigurer, Jackson2ObjectMapperBuilderCustomizer {
 +    @Override
 +    public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) {
 +        jacksonObjectMapperBuilder
 +                .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
 +                .timeZone(TimeZone.getDefault())
 +                .locale(Locale.getDefault())
 +                .simpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
 +    }
 +}
 </code> </code>
  
줄 154: 줄 188:
   * [[http://lewandowski.io/2016/02/formatting-java-time-with-spring-boot-using-json/|Formatting Java Time with Spring Boot using JSON | Craftsmanship Archives]]   * [[http://lewandowski.io/2016/02/formatting-java-time-with-spring-boot-using-json/|Formatting Java Time with Spring Boot using JSON | Craftsmanship Archives]]
   * [[https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#howto-customize-the-jackson-objectmapper|How to customize the Jackson ObjectMapper]]   * [[https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#howto-customize-the-jackson-objectmapper|How to customize the Jackson ObjectMapper]]
 +  * [[https://dzone.com/articles/spring-web-service-response-filtering|Spring Web Service Response Filtering - DZone Java]] - 응답 Json Filter
 +  * [[https://www.baeldung.com/spring-boot-formatting-json-dates|Formatting JSON Dates in Spring Boot | Baeldung]]
springframework/springboot/json.1543299156.txt.gz · 마지막으로 수정됨: 2018/11/27 15:12 저자 kwon37xi