天天看點

Spring MVC JSON自定義類型轉換

類型有很多,這裡隻用日期為例說明。

在spring mvc中存在兩大類的類型轉換,一類是json,一個是spring的binder轉換。

json:

使用json轉換時,可以如下使用:

[java] view

plain copy

Spring MVC JSON自定義類型轉換
Spring MVC JSON自定義類型轉換

public class test {  

    private date createdate;  

    @jsonserialize(using = dateymdhmsjsonserializer.class)  

    public date getcreatedate() {  

        return createdate;  

    }  

    @jsondeserialize(using = dateymdhmsjsondeserializer.class)  

    public void setcreatedate(date createdate) {  

        this.createdate = createdate;  

}  

可以看到這裡使用了兩個json轉換的注解:

第一個@jsonserialize是轉換為字元串,主要是背景傳遞給前台時的日期格式;

第二個@jsondeserialize是轉換字元串為日期類型,主要是從前台往背景傳遞時的日期。

兩個具體轉換類的實作:

Spring MVC JSON自定義類型轉換
Spring MVC JSON自定義類型轉換

/** 

 * description: 日期轉換 - "yyyy-mm-dd hh:mm:ss" 

 * author: liuzh 

 * update: liuzh(2014-04-17 10:59) 

 */  

public class dateymdhmsjsonserializer extends jsonserializer<date>{  

    @override  

    public void serialize(date date, jsongenerator jsongenerator, serializerprovider serializerprovider) throws ioexception, jsonprocessingexception {  

        try {  

            jsongenerator.writestring(dateutil.formatdate(date, dateutil.date_format_time_t));  

        } catch (businessexception e) {  

            jsongenerator.writestring(string.valueof(date.gettime()));  

        }  

Spring MVC JSON自定義類型轉換
Spring MVC JSON自定義類型轉換

public class dateymdhmsjsondeserializer extends jsondeserializer<date> {  

    public date deserialize(jsonparser jp, deserializationcontext ctxt) throws ioexception, jsonprocessingexception {  

            return dateutil.formatstringtodate(jp.gettext(), dateutil.date_format_time_t);  

            return new date(jp.getlongvalue());  

其中dateutil是一個對日期格式轉換的工具類,使用的simpledateformat進行轉換。

binder:

這種類型轉換的時候,使用的是spring的參數綁定,代碼如下:

Spring MVC JSON自定義類型轉換
Spring MVC JSON自定義類型轉換

 * description: 全局類型轉換 

 * update: liuzh(2014-05-26 13:08) 

public class globaldatabinder implements webbindinginitializer {  

    /** 

     * 智能日期轉換,針對四種格式日期: 

     * 1.2014-05-26 

     * 2.1401951570548 

     * 3.2014-05-26 00:00 

     * 4.2014-05-26 00:00:00 

     */  

    private class smartdateeditor extends propertyeditorsupport {  

        /** 

         * 根據2014-05-26 00:00:00長度來判斷選擇哪種轉換方式 

         */  

        @override  

        public void setastext(string text) throws illegalargumentexception {  

            if (text == null || text.length() == 0) {  

                setvalue(null);  

            } else {  

                try {  

                    if (text.length() == 10) {  

                        setvalue(dateutil.formatstringtodate(text, dateutil.date_format_yyyymmdd));  

                    } else if (text.length() == 13) {  

                        setvalue(new date(long.parselong(text)));  

                    } else if (text.length() == 16) {  

                        setvalue(dateutil.formatstringtodate(text, dateutil.date_format_time_r));  

                    } else if (text.length() == 19) {  

                        setvalue(dateutil.formatstringtodate(text, dateutil.date_format_time_t));  

                    } else {  

                        throw new illegalargumentexception("轉換日期失敗: 日期長度不符合要求!");  

                    }  

                } catch (exception ex) {  

                    throw new illegalargumentexception("轉換日期失敗: " + ex.getmessage(), ex);  

                }  

            }  

         * 轉換為日期字元串 

        public string getastext() {  

            date value = (date) getvalue();  

            string datestr = null;  

            if (value == null) {  

                return "";  

                    datestr = dateutil.formatdate(value, dateutil.date_format_time_t);  

                    if (datestr.endswith(" 00:00:00")) {  

                        datestr = datestr.substring(0, 10);  

                    } else if (datestr.endswith(":00")) {  

                        datestr = datestr.substring(0, 16);  

                    return datestr;  

    public void initbinder(webdatabinder binder, webrequest request) {  

        //日期格式轉換  

        binder.registercustomeditor(date.class, new smartdateeditor());  

這裡對日期類型進行了一些判斷來特殊處理。該類需要在spring的xml進行配置:

[html] view

Spring MVC JSON自定義類型轉換
Spring MVC JSON自定義類型轉換

<bean class="org.springframework.web.servlet.mvc.annotation.annotationmethodhandleradapter">  

    <property name="webbindinginitializer">  

      <bean class="com.easternie.sys.common.globaldatabinder"/>  

    </property>  

</bean>  

通過這種配置之後,spring就能對日期進行智能轉換了。