Joda DateTime을 ISO 8601 형식으로 자동 포맷
http://wiki.fasterxml.com/JacksonFAQDateHandling,에 따르면 "날짜 타임은 java.diserialize와 마찬가지로 자동으로 시리얼화/디시리얼화 할 수 있습니다.날짜는 처리됩니다."다만, 이 자동 기능은 사용할 수 없습니다.이 토픽과 관련된 Stack Overflow에 대한 논의는 있지만 대부분 코드 기반 솔루션에 관한 것이지만 위의 견적에 따르면 간단한 구성으로 이를 달성할 수 있을 것입니다.
http://wiki.fasterxml.com/JacksonFAQDateHandling 에 따라서, 타임스탬프로 날짜를 기입하는 것이 잘못되도록 설정이 되어 있습니다.그 결과 java.util이 생성됩니다.날짜 유형은 ISO 8601 형식으로 일련화되지만 org.joda.time으로 일련화됩니다.Date Time 유형은 긴 개체 표현에 직렬화됩니다.
내 환경은 다음과 같습니다.
잭슨 2.1
조다 시간 2.1
봄 3.2
자바 1.6
jsonMapper bean의 스프링 구성은 다음과 같습니다.
@Bean
public ObjectMapper jsonMapper() {
ObjectMapper objectMapper = new ObjectMapper();
//Fully qualified path shows I am using latest enum
ObjectMapper.configure(com.fasterxml.jackson.databind.SerializationFeature.
WRITE_DATES_AS_TIMESTAMPS , false);
return objectMapper;
}
제 테스트 코드 조각은 이것입니다.
Date d = new Date();
DateTime dt = new DateTime(d); //Joda time
Map<String, Object> link = new LinkedHashMap<String, Object>();
link.put("date", d);
link.put("createdDateTime", dt);
JSON 출력의 결과는 다음과 같습니다.
{"date":"2012-12-24T21:20:47.668+0000"}
{"createdDateTime": {"year":2012,"dayOfMonth":24,"dayOfWeek":1,"era":1,"dayOfYear":359,"centuryOfEra":20,"yearOfEra":2012,"yearOfCentury":12,"weekyear":2012,"monthOfYear":12 *... remainder snipped for brevity*}}
설정에 따라 Date Time 객체가 Date 객체의 그것과 일치해야 합니다.내가 뭘 잘못하고 있는 걸까, 아니면 뭘 오해하고 있는 걸까?Jackson 문서에서 자동으로 단어를 너무 많이 읽어서 ISO 8601은 아니지만 문자열 표현이 생성되었다는 사실이 광고된 자동 기능을 생성하고 있습니까?
잭슨 유저 메일 리스트에서 답변을 얻을 수 있었고, 초보자이기 때문에 공유해 드리고 싶었습니다.Jackson Date FAQ를 읽고 추가 의존관계와 등록이 필요한 줄은 몰랐지만, 그렇습니다.git hub project 페이지(https://github.com/FasterXML/jackson-datatype-joda에 기재되어 있습니다.
기본적으로 Joda 데이터 유형에 고유한 Jackson jar에 다른 종속성을 추가하고 그 모듈의 사용을 객체 매퍼에 등록해야 했습니다.코드 스니펫은 다음과 같습니다.
Jackson Joda 데이터 타입의 Maven 의존관계 설정에서는 다음을 사용했습니다.
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-joda</artifactId>
<version>${jackson.version}</version>
</dependency>
Joda 시리얼화/디시리얼화 기능을 등록하기 위해 다음을 사용했습니다.
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new JodaModule());
objectMapper.configure(com.fasterxml.jackson.databind.SerializationFeature.
WRITE_DATES_AS_TIMESTAMPS , false);
스프링 부트를 사용한다.
Maven 구성에 추가...
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-joda</artifactId>
<version>2.7.5</version>
</dependency>
다음으로 Web Configuration으로...
@Configuration
public class WebConfiguration extends WebMvcConfigurerAdapter
{
public void configureMessageConverters(List<HttpMessageConverter<?>> converters)
{
final MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
final ObjectMapper objectMapper = new ObjectMapper();
//configure Joda serialization
objectMapper.registerModule(new JodaModule());
objectMapper.configure(
com.fasterxml.jackson.databind.SerializationFeature.
WRITE_DATES_AS_TIMESTAMPS , false);
// Other options such as how to deal with nulls or identing...
objectMapper.setSerializationInclusion (
JsonInclude.Include.NON_NULL);
objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
converter.setObjectMapper(objectMapper);
converters.add(converter);
super.configureMessageConverters(converters);
}
}
Spring Boot에서는 설정이 더욱 심플합니다.방금 메이븐 의존을 선언했군요
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-joda</artifactId>
</dependency>
다음으로 설정 파라미터를 application.yml/properties 파일에 추가합니다.
spring.jackson.serialization.write-dates-as-timestamps: false
Spring 4.2.0을 사용하여 업데이트된 작업 예를 게시하려고 합니다.릴리스, 잭슨 2.6.1, 조다 2.8.2
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
">
<!-- DispatcherServlet Context: defines this servlet's request-processing
infrastructure -->
<!-- Enables the Spring MVC @Controller programming model -->
<annotation-driven>
<message-converters>
<beans:bean
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<beans:property name="objectMapper" ref="objectMapper" />
</beans:bean>
</message-converters>
</annotation-driven>
<!-- Handles HTTP GET requests for /resources/** by efficiently serving
up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by @Controllers to .jsp resources
in the /WEB-INF/views directory -->
<beans:bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<beans:bean id="objectMapper"
class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
<beans:property name="featuresToDisable">
<beans:array>
<util:constant
static-field="com.fasterxml.jackson.databind.SerializationFeature.WRITE_DATES_AS_TIMESTAMPS" />
</beans:array>
</beans:property>
<beans:property name="modulesToInstall"
value="com.fasterxml.jackson.datatype.joda.JodaModule" />
</beans:bean>
<beans:bean id="localeResolver"
class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
<beans:property name="defaultLocale" value="en" />
</beans:bean>
<!-- Configure the Message Locale Resources -->
<beans:bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<beans:property name="basename" value="errors" />
</beans:bean>
<beans:bean id="versionSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<beans:property name="basename" value="version" />
</beans:bean>
<!-- DataSource -->
<beans:bean id="dataSource"
class="org.springframework.jndi.JndiObjectFactoryBean">
<beans:property name="jndiName" value="java:comp/env/jdbc/TestDB" />
</beans:bean>
<!-- POJO: Configure the DAO Implementation -->
<beans:bean id="publicationsDAO"
class="com.test.api.publication.PublicationsDAOJdbcImpl">
<beans:property name="dataSource" ref="dataSource" />
</beans:bean>
<!-- Things to auto-load -->
<context:component-scan base-package="com.test.api" />
<context:component-scan base-package="com.test.rest" />
</beans:beans>
API 코드
package com.test.api.publication;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName("event")
@JsonIgnoreProperties(ignoreUnknown=true)
public class Publication {
private Map<String, Object> tokens;
private String href;
private String policy_path;
@JsonProperty("tokens")
public Map<String, Object> getTokens() {
return tokens;
}
@JsonProperty("tokens")
public void setTokens(Map<String, Object> tokens) {
this.tokens = tokens;
}
@JsonProperty("href")
public String getHref() {
return href;
}
@JsonProperty("href")
public void setHref(String href) {
this.href = href;
}
@JsonProperty("policyPath")
public String getPolicyPath() {
return policy_path;
}
@JsonProperty("policyPath")
public void setPolicyPath(String policy_path) {
this.policy_path = policy_path;
}
}
package com.test.api.publication;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class PublicationsDAOJdbcImpl implements PublicationsDAO{
static final Logger logger = LoggerFactory.getLogger(PublicationsDAOJdbcImpl.class.getName());
private DataSource _dataSource;
@Override
public void setDataSource(DataSource ds) {
// TODO Auto-generated method stub
}
@Override
public void close() {
// TODO Auto-generated method stub
}
@Override
public Publication getPublication(String policyPath) {
Publication ret = new Publication();
//TODO: do something
return ret;
}
}
package com.test.rest.publication;
import java.util.HashMap;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.test.api.publication.Publication;
import com.test.api.publication.PublicationsDAO;
import com.test.rest.error.UnknownResourceException;
@RestController
@RequestMapping("/pub")
public class PublicationController {
private static final Logger logger = LoggerFactory.getLogger(PublicationController.class);
@Autowired
@Qualifier("publicationsDAO")
private PublicationsDAO publicationsDAO;
/**********************************************************************************************************************
*
* @param policyPath
* @return
* @throws UnknownResourceException
*/
@RequestMapping(value = "/{policyPath}", method = RequestMethod.GET)
public Publication getByPolicyPath(@PathVariable String policyPath) throws UnknownResourceException{
logger.debug("policyPath=" + policyPath);
Publication ret = publicationsDAO.getPublication(policyPath);
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("TEST1", null);
map.put("TEST2", new Integer(101));
map.put("TEST3", "QuinnZilla");
map.put("TEST4", new DateTime());
ret.setTokens(map);
return ret;
}
}
그리고 나는 결과물을 얻었다.
{
"tokens": {
"TEST2": 101,
"TEST3": "QuinnZilla",
"TEST4": "2015-10-06T16:59:35.120Z",
"TEST1": null
},
"href": null,
"policyPath": null
}
언급URL : https://stackoverflow.com/questions/14026081/jackson-automatic-formatting-of-joda-datetime-to-iso-8601-format
'programing' 카테고리의 다른 글
개체를 배열에 푸시하려면 어떻게 해야 합니까? (0) | 2023.03.10 |
---|---|
MongoDB에서 대소문자를 구분하지 않는 정렬 (0) | 2023.03.10 |
주문 에이잭스에 수수료를 추가하는 woocommerce 커스텀 체크아웃 필드 (0) | 2023.03.10 |
구성 요소 속성이 현재 날짜/시간에 따라 달라지는 경우 Angular2 "체크된 후 식이 변경되었습니다" 예외를 관리하는 방법 (0) | 2023.03.10 |
Xmlhttp 요청 리디렉션 방지 (0) | 2023.03.10 |