杰克逊和空弦

时间:2013-06-14 01:31:56

标签: java json jackson

我有以下代码:

import javax.xml.datatype.XMLGregorianCalendar;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.fasterxml.jackson.databind.SerializationFeature;

    public class Test {

        public static void main(String[] args) {
            print("");//Prints null
            print("2013-06-14T01:23:47.547+0000"); //Prints the date
            print("&&&&AD");//Throws error
        }

        private static void print(String dateString) {
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false );
            try {
                String x = "{\"dateTime\": \""+dateString+"\"}";
                Foo type = mapper.readValue(x, Foo.class);
                System.out.println("Datetime is " + type.getDateTime());
            } catch (Exception e) {
                e.printStackTrace();
            } 
        }

        private static class Foo {

            private XMLGregorianCalendar dateTime;
            public XMLGregorianCalendar getDateTime() {
                return dateTime;
            }
            public void setDateTime(XMLGregorianCalendar dateTime) {
                this.dateTime = dateTime;
            }

        }

    }

当String值为空白“”时,Jackson会将该值视为空,但是当我输入一些无效值,例如“&&&& AD”时,它会尝试将其转换为XML日期时间并抛出错误。

我得到的错误是:

com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not construct instance of javax.xml.datatype.XMLGregorianCalendar from String value '&&&&AD': not a valid representation (error: Failed to parse Date value '&&&&AD': Can not parse date "&&&&AD": not compatible with any of standard forms ("yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "EEE, dd MMM yyyy HH:mm:ss zzz", "yyyy-MM-dd"))

我想看到空白值的相同行为。我该怎么做?

有没有办法让杰克逊失败以获得空白值?

1 个答案:

答案 0 :(得分:2)

您必须为XMLGregorianCalendar类型实现新的反序列化器。它看起来像这样:

class XMLGregorianCalendarDeserializer extends GregorianCalendarDeserializer {

    private static final long serialVersionUID = 1L;

    @Override
    public XMLGregorianCalendar deserialize(JsonParser jp, DeserializationContext ctxt)
            throws IOException {
        try {
            return super.deserialize(jp, ctxt);
        } catch (JsonProcessingException e) {
            return null;
        }
    }
}

之后你必须在POJO类中定义反序列化器:

class Foo {

    @JsonDeserialize(using = XMLGregorianCalendarDeserializer.class)
    private XMLGregorianCalendar dateTime;

    ...
}