Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package com.fasterxml.jackson.databind.deser.std;
  
  import java.sql.Timestamp;
  import java.text.*;
  import java.util.*;
  
  
 
Container class for core JDK date/time type deserializers.
 
 @SuppressWarnings("serial")
 public class DateDeserializers
 {
     private final static HashSet<String_classNames = new HashSet<String>();
     static {
         Class<?>[] numberTypes = new Class<?>[] {
             Calendar.class,
             GregorianCalendar.class,
             java.sql.Date.class,
             java.util.Date.class,
             Timestamp.class,
             TimeZone.class
         };
         for (Class<?> cls : numberTypes) {
             .add(cls.getName());
         }
     }
 
     public static JsonDeserializer<?> find(Class<?> rawTypeString clsName)
     {
         if (!.contains(clsName)) {
             return null;
         }
         // Start with the most common type
         if (rawType == Calendar.class) {
             return .;
         }
         if (rawType == java.util.Date.class) {
             return .;
         }
         if (rawType == java.sql.Date.class) {
             return .;
         }
         if (rawType == Timestamp.class) {
             return .;
         }
         if (rawType == TimeZone.class) {
             return .;
         }
         if (rawType == GregorianCalendar.class) {
             return .;
         }
         // should never occur
         throw new IllegalArgumentException("Internal error: can't find deserializer for "+clsName);
     }
     
     /*
     /**********************************************************
     /* Intermediate class for Date-based ones
     /**********************************************************
      */
 
     protected abstract static class DateBasedDeserializer<T>
         extends StdScalarDeserializer<T>
         implements ContextualDeserializer
     {
        
Specific format to use, if non-null; if null will just use default format.
 
         protected final DateFormat _customFormat;

        
Let's also keep format String for reference, to use for error messages
 
         protected final String _formatString;
         
         protected DateBasedDeserializer(Class<?> clz) {
             super(clz);
              = null;
              = null;
         }
 
         protected DateBasedDeserializer(DateBasedDeserializer<T> base,
                DateFormat formatString formatStr) {
            super(base._valueClass);
             = format;
             = formatStr;
        }
        protected abstract DateBasedDeserializer<T> withDateFormat(DateFormat dfString formatStr);
        
        @Override
        public JsonDeserializer<?> createContextual(DeserializationContext ctxtBeanProperty property)
           throws JsonMappingException
        {
            if (property != null) {
                JsonFormat.Value format = ctxt.getAnnotationIntrospector().findFormat((Annotatedproperty.getMember());
                if (format != null) {
                    TimeZone tz = format.getTimeZone();
                    // First: fully custom pattern?
                    String pattern = format.getPattern();
                    if (pattern.length() > 0){
                        Locale loc = format.getLocale();
                        if (loc == null) {
                            loc = ctxt.getLocale();
                        }
                        SimpleDateFormat df = new SimpleDateFormat(patternloc);
                        if (tz == null) {
                            tz = ctxt.getTimeZone();
                        }
                        df.setTimeZone(tz);
                        return withDateFormat(dfpattern);
                    }
                    // But if not, can still override timezone
                    if (tz != null) {
                        DateFormat df = ctxt.getConfig().getDateFormat();
                        // one shortcut: with our custom format, can simplify handling a bit
                        if (df.getClass() == StdDateFormat.class) {
                            df = ((StdDateFormatdf).withTimeZone(tz);
                        } else {
                            // otherwise need to clone, re-set timezone:
                            df = (DateFormatdf.clone();
                            df.setTimeZone(tz);
                        }
                        return withDateFormat(dfpattern);
                    }
                }
            }
            return this;
        }
        
        @Override
        protected java.util.Date _parseDate(JsonParser jpDeserializationContext ctxt)
            throws IOExceptionJsonProcessingException
        {
            if ( != null && jp.getCurrentToken() == .) {
                String str = jp.getText().trim();
                if (str.length() == 0) {
                    return (DategetEmptyValue();
                }
                synchronized () {
                    try {
                        return .parse(str);
                    } catch (ParseException e) {
                        throw new IllegalArgumentException("Failed to parse Date value '"+str
                                +"' (format: \""++"\"): "+e.getMessage());
                    }
                }
            }
            return super._parseDate(jpctxt);
        }
    }
    
    /*
    /**********************************************************
    /* Deserializer implementations for Date types
    /**********************************************************
     */
    
    public static class CalendarDeserializer
        extends DateBasedDeserializer<Calendar>
    {
        public final static CalendarDeserializer instance = new CalendarDeserializer();
        public final static CalendarDeserializer gregorianInstance = new CalendarDeserializer(GregorianCalendar.class);
        
        
We may know actual expected type; if so, it will be used for instantiation.
        protected final Class<? extends Calendar_calendarClass;
        
        public CalendarDeserializer() {
            super(Calendar.class);
             = null;
        }
        public CalendarDeserializer(Class<? extends Calendarcc) {
            super(cc);
             = cc;
        }
        public CalendarDeserializer(CalendarDeserializer srcDateFormat dfString formatString) {
            super(srcdfformatString);
             = src._calendarClass;
        }
        @Override
        protected CalendarDeserializer withDateFormat(DateFormat dfString formatString) {
            return new CalendarDeserializer(thisdfformatString);
        }
        
        @Override
        public Calendar deserialize(JsonParser jpDeserializationContext ctxt)
            throws IOExceptionJsonProcessingException
        {
            Date d = _parseDate(jpctxt);
            if (d == null) {
                return null;
            }
            if ( == null) {
                return ctxt.constructCalendar(d);
            }
            try {
                Calendar c = .newInstance();            
                c.setTimeInMillis(d.getTime());
                TimeZone tz = ctxt.getTimeZone();
                if (tz != null) {
                    c.setTimeZone(tz);
                }
                return c;
            } catch (Exception e) {
                throw ctxt.instantiationException(e);
            }
        }
    }

    
Simple deserializer for handling java.util.Date values.

One way to customize Date formats accepted is to override method com.fasterxml.jackson.databind.DeserializationContext.parseDate(java.lang.String) that this basic deserializer calls.

    public static class DateDeserializer
        extends DateBasedDeserializer<Date>
    {
        public final static DateDeserializer instance = new DateDeserializer();
        public DateDeserializer() { super(Date.class); }
        public DateDeserializer(DateDeserializer baseDateFormat dfString formatString) {
            super(basedfformatString);
        }
        @Override
        protected DateDeserializer withDateFormat(DateFormat dfString formatString) {
            return new DateDeserializer(thisdfformatString);
        }
        
        @Override
        public java.util.Date deserialize(JsonParser jpDeserializationContext ctxt)
            throws IOExceptionJsonProcessingException
        {
            return _parseDate(jpctxt);
        }
    }

    
Compared to plain old java.util.Date, SQL version is easier to deal with: mostly because it is more limited.
    public static class SqlDateDeserializer
        extends DateBasedDeserializer<java.sql.Date>
    {
        public final static SqlDateDeserializer instance = new SqlDateDeserializer();
        public SqlDateDeserializer() { super(java.sql.Date.class); }
        public SqlDateDeserializer(SqlDateDeserializer srcDateFormat dfString formatString) {
            super(srcdfformatString);
        }
        @Override
        protected SqlDateDeserializer withDateFormat(DateFormat dfString formatString) {
            return new SqlDateDeserializer(thisdfformatString);
        }
        
        @Override
        public java.sql.Date deserialize(JsonParser jpDeserializationContext ctxt)
            throws IOExceptionJsonProcessingException
        {
            Date d = _parseDate(jpctxt);
            return (d == null) ? null : new java.sql.Date(d.getTime());
        }
    }

    
Simple deserializer for handling java.sql.Timestamp values.

One way to customize Timestamp formats accepted is to override method com.fasterxml.jackson.databind.DeserializationContext.parseDate(java.lang.String) that this basic deserializer calls.

    public static class TimestampDeserializer
        extends DateBasedDeserializer<Timestamp>
    {
        public final static TimestampDeserializer instance = new TimestampDeserializer();
        public TimestampDeserializer() { super(Timestamp.class); }
        public TimestampDeserializer(TimestampDeserializer srcDateFormat dfString formatString) {
            super(srcdfformatString);
        }
        @Override
        protected TimestampDeserializer withDateFormat(DateFormat dfString formatString) {
            return new TimestampDeserializer(thisdfformatString);
        }
        
        @Override
        public java.sql.Timestamp deserialize(JsonParser jpDeserializationContext ctxt)
            throws IOExceptionJsonProcessingException
        {
            return new Timestamp(_parseDate(jpctxt).getTime());
        }
    }
    /*
    /**********************************************************
    /* Deserializer implementations for Date-related types
    /**********************************************************
     */
    
    
As per [JACKSON-522], also need special handling for TimeZones
    protected static class TimeZoneDeserializer
        extends FromStringDeserializer<TimeZone>
    {
        public final static TimeZoneDeserializer instance = new TimeZoneDeserializer();
        public TimeZoneDeserializer() { super(TimeZone.class); }
        @Override
        protected TimeZone _deserialize(String valueDeserializationContext ctxt)
            throws IOException
        {
            return TimeZone.getTimeZone(value);
        }
    }
New to GrepCode? Check out our FAQ X