如何在序列化和反序列化对象时解决InvalidDefinitionException

时间:2019-07-27 20:35:44

标签: jackson avro jackson-dataformat-avro

在尝试使用Avro格式对POJO进行序列化/反序列化时,我们看到了InvalidDefinitionException。我在日期字段上使用了@JsonDeserialize和@JsonSerialize批注。

当尝试序列化对象时,我们看到以下异常 异常堆栈是

  com.fasterxml.jackson.databind.exc.InvalidDefinitionException: "Any" type (usually for `java.lang.Object`) not supported: `expectAnyFormat` called with type [simple type, class java.util.Date]
at com.fasterxml.jackson.databind.exc.InvalidDefinitionException.from(InvalidDefinitionException.java:77)
at com.fasterxml.jackson.dataformat.avro.schema.VisitorFormatWrapperImpl.expectAnyFormat(VisitorFormatWrapperImpl.java:174)
at com.fasterxml.jackson.databind.JsonSerializer.acceptJsonFormatVisitor(JsonSerializer.java:275)

我还缺少其他设置吗?

Person.java

public class Person {

public String getfName() {
    return fName;
}
public void setfName(String fName) {
    this.fName = fName;
}
public String getlName() {
    return lName;
}
public void setlName(String lName) {
    this.lName = lName;
}
@JsonDeserialize(using = 
        com.sample.DateDeserializer.class)
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL, using = 
        com.sample.DateSerializer.class)
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd", locale = "en_US", timezone ="EST")
public Date getDob() {
    return dob;
}
public void setDob(Date dob) {
    this.dob = dob;
}
private String fName;
private String lName;
private Date dob;
}

测试

  LocalDate localDate = LocalDate.parse("2019-01-01",DateTimeFormatter.ofPattern("yyyy-MM-dd"));
  Date date = 
    Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
  Person person = new Person("abc","xyz",date );
  AvroMapper avroMapper = new AvroMapper();
  AvroSchema schema = avroMapper.schemaFor(Person.class);
  ObjectWriter objectWriter = avroMapper.writer(schema);
  ObjectReader objectReader = avroMapper
                .readerFor(Person.class)
                .with(schema);
  ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
  objectWriter.writeValue(bos,person);
  System.out.println(bos.toString());
  System.out.println(objectReader.readValue(bos.toByteArray()));

经过一番尝试和错误之后,我认为问题更多在于@JsonSerialize批注。如果我注释该批注,则avro序列化和反序列化工作正常。

 @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL, using = 
        com.sample.DateSerializer.class)

我了解@JsonFormat可能正在执行与@JsonSerialize相同的操作,但不确定为什么@JsonFormat可以工作,但是@JsonSerialize不能

0 个答案:

没有答案
相关问题