Search code examples
javaarraysapache-kafkaavro

How can we access the array fields from Avro Schema in the Kafka producer code?


I have the below Avro Schema:

    `{
      "name": "ABC",
      "type": "record",
      "namespace": "com.schema.avro",
      "fields": [
        {
          "name": "str1",
          "type": "string"
        },
        {
          "name": "arrData",
          "type":["null",
          {
            "type": "array",
            "items": {
              "name": "arrData_record",
              "type": "record",
              "fields": [
                {
                  "name": "var1",
                  "type": ["null","string"],
                  "default": null
                },
                {
                  "name": "var2",
                  "type": ["null","int"],
                  "default": null
                }
              ]
            }
          }
          ],
          "default": null
        }
      ]
    }`

I used the POM.XML Maven plugin to generate the classes. Below 2 classes were generated from the plugin- i) ABC
ii) arrData_record

I am able to use the field str1 from ABC as below:

    ABC abc = ABC.newBuilder()
           .setStr1("random value")
           .build()

Similarly, I am also getting an option to use .setArrData().

I want to set the array fields in a similar way using .setVar1() and .setVar2().

How can I use the fields from the Array class and set it similarly? Any sample code would be of great help.

Thanks.


Solution

  • The generated class from the Avro schema could be manipulated like this

    ABC
        .newBuilder()
        .setArrData(Collections.singletonList(arrData_record
            .newBuilder()
            .setVar1("Var1")
            .setVar2(2)
            .build()))
        .build();