Two steps to convert any pojo class to avro genric record
Using jackson/avro, to convert the pojo into bytes with Avro Mapper.
Using Avro GenericDatumReader to read it as Generic Record.
public class AvroConverter{
public static GenericRecord convertToGenericRecord(String schemaPath, SomeClass someObject){
Schema schema = new Schema.Parser().setValidate(true).parse(new ClassPathResource(schemaPath).getFile());
AvroSchema avSchema = new AvroSchema(schema);
ObjectWritter writter = new AvroMapper().writer(avSchema);
final byte[] bytes = objectWriter.writeValueAsBytes(someObject);
GenericDatumReader<Object> genericRecordReader = new GenericDatumReader<>(avSchema);
return (GenericRecord) genericRecordReader.read(null, DecoderFactory.get().binaryDecoder(bytes, null));
}
}
Gradle Dependency
implementation 'com.fasterxml.jackson.dataformat:jackson-dataformat-avro'
While doing serialization, you may face issues. For that, you have to configure the avro mapper properties