0

Please find below two classes :

Parent class

@Data
public class Parent
{
  private String lan;

  private Child childClass;

}

Child class

@Data
public class Child 
{
  private BigDecimal total;

  @AvroEncode(using = LocalDateAsStringAvroEncoding.class)
  private LocalDate firstDefaultDate;

  @AvroEncode(using = LocalDateAsStringAvroEncoding.class)
  private LocalDate secondDefaultDate;
}

Code for the custom serializer

public class LocalDateAsStringAvroEncoding extends CustomEncoding<LocalDate> {

    public LocalDateAsStringAvroEncoding() {
        // Define schema for this field
        this.schema = (Schema)((SchemaBuilder.StringBldr) SchemaBuilder.builder().stringBuilder().prop
                ("CustomEncoding", LocalDateAsStringAvroEncoding.class.getName())).endString();
    }

    @Override
    protected void write(Object datum, Encoder encoder) throws IOException {
        encoder.writeString(datum.toString());
    }

    @Override
    protected LocalDate read(Object datum, Decoder decoder) throws IOException {
        try {
            return LocalDate.parse(decoder.readString());
        } catch (Exception e) {
            throw new IllegalStateException("Could not decode String into LocalDate", e);
        }
    }
}

Code for the serialization function

private static byte[] serializeData(Parent parent){
        byte[] data = new byte[0];
        ReflectData reflectData = ReflectData.AllowNull.get();
        Schema schema = reflectData.getSchema(Parent.class);
        DatumWriter<Parent> writer = new ReflectDatumWriter<Parent>(schema);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        Encoder jsonEncoder = null;
        try{
            jsonEncoder = EncoderFactory.get().binaryEncoder(stream,null);
            writer.write(parent,jsonEncoder);
            jsonEncoder.flush();
            data = stream.toByteArray();
        }catch(Exception ex){
            System.out.println(ex);
        }
        return data;
    }

Now I am getting the following exception

java.lang.NullPointerException: null of ChildClass in ChildClass of union in union in field childClass of Parent in Parent

when I pass the following class for serialization, when the value is null for one of the fields which I am using a custom encoder on it throws an exception.

{
"lan" : "12345",
"childClass" : {
"total" : "100",
"firstDefaultDate" : "2022-02-21T22:22:04.102",
"secondDefaultDate" : null
}
}

Can anyone please help me with this? Thank you.

Aditya
  • 1

0 Answers0