Springmvc統一設置返回到前端的json時間格式


 

 
        

我們在使用springmvc中的 @ResponseBody 注解往前端返回JSON數據的時候發現時間總是一串數字,這里總結使用的兩種解決時間格式問題的方法。

 
        

1、在時間字段的get方法上使用注解

@JsonFormat(pattern ="yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")

這樣前端獲取的時間就是你設置的時間格式。但是這種方法是個體力活,每個時間類型的字段你都需要給加上這個注解。

 
        

2、通過在spring xml配置文件里配置Json轉換器設置時間格式 

@Component("jacksonObjectMapper") 與配置文件里的ref指向名稱相對應

public class CustomObjectMapper extends ObjectMapper {

private static final long serialVersionUID = 1L;

@PostConstruct

public void afterPropertiesSet() throws Exception {

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

setDateFormat(sdf);

}

}
spring的xml文件配置
 
        
<mvc:annotation-driven>
        <mvc:message-converters>     
            <beans:bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <beans:property name="objectMapper" ref="jacksonObjectMapper"/>
                <property name="supportedMediaTypes">
                    <list>
                        <value>application/json;charset=UTF-8</value>
                    </list>
                </property>
            </beans:bean>         
        </mvc:message-converters>
    </mvc:annotation-driven>


免責聲明!

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



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