JSON Serializing date in a custom format (Can not construct instance of java.util.Date from String value)

后端 未结 6 1419
野的像风
野的像风 2020-12-03 07:01
could not read JSON: Can not construct instance of java.util.Date from String 
value \'2012-07-21 12:11:12\': not a valid representation(\"yyyy-MM-dd\'T\'HH:mm:ss.SS         


        
6条回答
  •  既然无缘
    2020-12-03 07:40

    Yet another way is to have a custom Date object which takes care of its own serialization.

    While I don't really think extending simple objects like Date, Long, etc. is a good practice, in this particular case it makes the code easily readable, has a single point where the format is defined and is rather more than less compatible with normal Date object.

    public class CustomFormatDate extends Date {
    
        private DateFormat myDateFormat = ...; // your date format
    
        public CustomFormatDate() {
            super();
        }
    
        public CustomFormatDate(long date) {
            super(date);
        }
    
        public CustomFormatDate(Date date) {
            super(date.getTime());
        }
    
    
        @JsonCreator
        public static CustomFormatDate forValue(String value) {
            try {
                return new CustomFormatDate(myDateFormat.parse(value));
            } catch (ParseException e) {
                return null;
            }
        }
    
        @JsonValue
        public String toValue() {
            return myDateFormat.format(this);
        }
    
        @Override
        public String toString() {
            return toValue();
        }
    }
    

提交回复
热议问题