springmvc返回json數據時,日期數據顯示為數字的解決方式


(1)@JsonFormat注解;

可以在get方法上,或屬性上使用@JsonFormat(pattern="yyyy-MM-dd");而且指定對象以json傳遞時,顯示的日期格式,優先級高於全局變量;即第一種和第二種方法如果同時存在,會以第一種的格式為准;

    //指定對象以json格式傳遞時,顯示的日期格式 ,優先級高於全局配置
    @JsonFormat(pattern = "yyyy-MM-dd")
    private Date birthday;

(2)在springmvc的配置文件中做全局配置;

<!--設置返回json格式數據時,日期格式 ,當某些需要特殊處理,不按此方式來時,
      在get方法上,或屬性上使用@JsonFormat(pattern="yyyy-MM-dd",timezone = "GMT+8")-->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="messageConverters">
            <list>
            <bean class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter" />
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" >
                <property name="objectMapper">
                    <bean class="com.fasterxml.jackson.databind.ObjectMapper">
                        <property name="dateFormat">
                            <bean class="java.text.SimpleDateFormat">
                                <!-- 設置全局返回JSON到前端時日期格式化 -->
                                <constructor-arg type="java.lang.String" value="yyyy-MM-dd HH:mm:ss"/>
                            </bean>
                        </property>
                    </bean>
                </property>
            </bean>
            </list>
        </property>
    </bean>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM