zoukankan      html  css  js  c++  java
  • Spring MVC JSON自己定义类型转换

    版权声明:版权归博主全部。转载请带上本文链接。联系方式:abel533@gmail.com https://blog.csdn.net/isea533/article/details/28625071

    类型有非常多。这里仅仅用日期为例说明。


    在Spring MVC中存在两大类的类型转换,一类是Json。一个是Spring的Binder转换。


    JSON:

    使用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是转换字符串为日期类型。主要是从前台往后台传递时的日期。


    两个详细转换类的实现:

    /**
     * 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()));
            }
        }
    }

    /**
     * Description: 日期转换 - "yyyy-MM-dd HH:mm:ss"
     * Author: liuzh
     * Update: liuzh(2014-04-17 10:59)
     */
    public class DateYMDHMSJsonDeserializer extends JsonDeserializer<Date> {
        @Override
        public Date deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
            try {
                return DateUtil.formatStringToDate(jp.getText(), DateUtil.DATE_FORMAT_TIME_T);
            } catch (BusinessException e) {
                return new Date(jp.getLongValue());
            }
        }
    }

    当中DateUtil是一个对日期格式转换的工具类,使用的SimpleDateFormat进行转换。


    Binder:

    这样的类型转换的时候,使用的是Spring的參数绑定,代码例如以下:

    /**
     * Description: 全局类型转换
     * Author: liuzh
     * 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);
                    }
                }
            }
    
            /**
             * 转换为日期字符串
             */
            @Override
            public String getAsText() {
                Date value = (Date) getValue();
                String dateStr = null;
                if (value == null) {
                    return "";
                } else {
                    try {
                        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;
                    } catch (Exception ex) {
                        throw new IllegalArgumentException("转换日期失败: " + ex.getMessage(), ex);
                    }
                }
            }
        }
    
        @Override
        public void initBinder(WebDataBinder binder, WebRequest request) {
            //日期格式转换
            binder.registerCustomEditor(Date.class, new SmartDateEditor());
        }
    
    }

    这里对日期类型进行了一些推断来特殊处理。

    该类须要在Spring的xml进行配置:

    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="webBindingInitializer">
          <bean class="com.easternie.sys.common.GlobalDataBinder"/>
        </property>
    </bean>
    通过这样的配置之后。Spring就能对日期进行智能转换了。





查看全文
  • 相关阅读:
    .Net魔法堂:史上最全的ActiveX开发教程——发布篇
    .Net魔法堂:史上最全的ActiveX开发教程——开发篇
    JS魔法堂:浏览器模式和文档模式怎么玩?
    JS魔法堂:精确判断IE的文档模式by特征嗅探
    JS魔法堂:追忆那些原始的选择器
    意译:自调用函数表达式
    一起Polyfill系列:让Date识别ISO 8601日期时间格式
    一起Polyfill系列:Function.prototype.bind的四个阶段
    poco 线程库
    CDN理解<转>
  • 原文地址:https://www.cnblogs.com/ldxsuanfa/p/10479262.html
  • Copyright © 2011-2022 走看看