Set Jackson Timezone for Date deserialization

后端 未结 9 620
终归单人心
终归单人心 2020-12-13 04:23

I\'m using Jackson (via Spring MVC Annotations) to deserialize a field into a java.util.Date from JSON. The POST looks like - {\"enrollDate\":\"2011-09-28

9条回答
  •  情话喂你
    2020-12-13 05:00

    I had same problem with Calendar deserialization, solved extending CalendarDeserializer.
    It forces UTC Timezone
    I paste the code if someone need it:

    @JacksonStdImpl
    public class UtcCalendarDeserializer extends CalendarDeserializer {
    
        TimeZone TZ_UTC = TimeZone.getTimeZone("UTC");
    
        @Override
        public Calendar deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
            JsonToken t = jp.getCurrentToken();
            if (t == JsonToken.VALUE_NUMBER_INT) {
                Calendar cal = Calendar.getInstance(TZ_UTC);
                cal.clear();
                cal.setTimeInMillis(jp.getLongValue());
    
                return cal;
            }
    
            return super.deserialize(jp, ctxt);
        }
    }
    

    in JSON model class just annotate the field with:

    @JsonDeserialize(using = UtcCalendarDeserializer.class)
    private Calendar myCalendar;
    

提交回复
热议问题