복붙노트

[SPRING] Spring 3.1 JSON 날짜 형식

SPRING

Spring 3.1 JSON 날짜 형식

주석 3.1 Spring MVC 코드 (spring-mvc)를 사용하고 있습니다. @RequestBody를 통해 date 객체를 보내면 날짜가 숫자로 표시됩니다. 이게 내 컨트롤러 야.

@Controller
@RequestMapping("/test")
public class MyController {

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(Date.class,
                  new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),true));
    }


    @RequestMapping(value = "/getdate", method = RequestMethod.GET)
    public @ResponseBody Date getDate(@RequestParam("dt") Date dt, Model model) {
        // dt is properly constructed here..
        return new Date();
    }
}

제가 날짜를 지날 때, 나는 형식으로 날짜를받을 수 있습니다. 하지만 브라우저에서 날짜를 숫자로 표시합니다.

1327682374011

웹 바인더에 등록한 형식으로 날짜를 표시하려면 어떻게합니까? 일부 포럼에서 잭슨 매퍼를 사용해야한다는 것을 알았지 만 기존의 매퍼를 바꿀 수 있습니까?

해결법

  1. ==============================

    1.Jakson의 기본 날짜 형식 전략을 재정의하려면 다음 단계를 따르십시오.

    Jakson의 기본 날짜 형식 전략을 재정의하려면 다음 단계를 따르십시오.

    암호:

    //CustomDateSerializer class
    public class CustomDateSerializer extends JsonSerializer<Date> {    
        @Override
        public void serialize(Date value, JsonGenerator gen, SerializerProvider arg2) throws 
            IOException, JsonProcessingException {      
    
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            String formattedDate = formatter.format(value);
    
            gen.writeString(formattedDate);
    
        }
    }
    
    
    //date getter method
    @JsonSerialize(using = CustomDateSerializer.class)
    public Date getDate() {
        return date;
    }
    

    출처 : http://blog.seyfi.net/2010/03/how-to-control-date-formatting-when.html

  2. ==============================

    2.또는 jackson을 사용하고 ISO-8601 날짜를 원할 경우 (주석 달기는 물론) 모든 날짜를 타임 스탬프로 사용하지 않도록 설정할 수 있습니다.

    또는 jackson을 사용하고 ISO-8601 날짜를 원할 경우 (주석 달기는 물론) 모든 날짜를 타임 스탬프로 사용하지 않도록 설정할 수 있습니다.

    <bean id="jacksonObjectMapper" class="org.codehaus.jackson.map.ObjectMapper"/>
    <bean id="jacksonSerializationConfig" class="org.codehaus.jackson.map.SerializationConfig" factory-bean="jacksonObjectMapper" factory-method="getSerializationConfig" />
    <bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
        <property name="targetObject" ref="jacksonSerializationConfig" />
        <property name="targetMethod" value="disable" />
        <property name="arguments">
            <list>
                <value type="org.codehaus.jackson.map.SerializationConfig.Feature">WRITE_DATES_AS_TIMESTAMPS</value>
            </list>
        </property>
    </bean>
    

    그런 다음 날짜를 기본값이 아닌 다른 형식으로 변환하려면 다음을 수행하십시오.

    <bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
        <property name="targetObject" ref="jacksonSerializationConfig" />
        <property name="targetMethod" value="setDateFormat" />
        <property name="arguments">
            <list>
              <bean class="java.text.SimpleDateFormat">
                <constructor-arg value="yyyy-MM-dd'T'HH:mm:ssZ"/>
              </bean>
            </list>
        </property>
    </bean>
    
  3. ==============================

    3.다음은 API에 권장하는 ISO8601 날짜를 사용하여이를 구성하는 표준 방법입니다.

    다음은 API에 권장하는 ISO8601 날짜를 사용하여이를 구성하는 표준 방법입니다.

    <!-- you can't call it objectMapper for some reason -->
    <bean name="jacksonObjectMapper" class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
        <property name="featuresToDisable">
            <array>
                <util:constant static-field="com.fasterxml.jackson.databind.SerializationFeature.WRITE_DATES_AS_TIMESTAMPS"/>
            </array>
        </property>
    </bean>
    
    <!-- setup spring MVC -->
    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="objectMapper" ref="jacksonObjectMapper"/>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>
    

    추가 문서는 다음과 같습니다.

  4. from https://stackoverflow.com/questions/9038005/spring-3-1-json-date-format by cc-by-sa and MIT license