Access custom attributes in avro schema from Java class

118 views Asked by At

I have some data that follows an avro schema given below. I generated Java classes from this schema by compiling it using avro-tools utility. However the Java classes contain only standard getters and setters and constructors. How do I access the value of custom attribute "mapto" in my java code. The intention is to transform the input avro file to an output avro file where the output field names come from the "mapto" field.

 {
   "type":"record",
   "name":"Products",
   "namespace":"com.example.datasets",
   "fields":[
      {
         "name":"ProductDetails",
         "type":["null",{
            "type":"record",
            "name":"ProductDetailsRecord",
            "fields":[
               {
                  "name":"itemName",
                  "type":["null","string"],
                  "default":null,
                  "mapto":"productName"
               },
               {
                  "name":"itemCode",
                  "type":["null","string"],
                  "default":null,
                  "mapto":"productId"
               }
               ]
         }]
      }
   
   ]
}
1

There are 1 answers

0
sawim On
// I assume details is not null
ProductDetailsRecord details;
for (var avroField : details.getSchema().getFields()) {
  var value = details.get(avroField.name());
  var mapTo = avroField.getProp("mapto");
}

Schema class also has getType method, which may be useful for you to recursively access nested fields of Products class