首页 > 解决方案 > How to validate record value with UNION type of avro schema in Java

问题描述

I am working on validating record data against avro schema. Following is my schema which has union type:

{
   "type":"record",
   "name":"event",
   "namespace":"test",
   "fields":[
      {
         "name":"email",
         "type":[
            "null",
            {
               "type":"string",
               "avro.java.string":"String"
            }
         ]
      }
   ]
}

And my record is:

{
   "emailAddress":"test@gmail.com"
}

Now I want to validate this specific field that it has a right type or not. Following is my Java code

// Schema
Schema dataSchema = schema.getField("data").schema();
// Converting my record into map
Map<String, Object> kafkaEvent = CustomRuleUtils.jsonStringToMap((String) kafkaEventData);
// Checking each field of schema (type and value) against this map
for (Schema.Field field : dataSchema.getFields()) {
    // if record has that field (emailAddress)
    if (kafkaEvent.get(field.name()) != null) {
        // want to check type of this record is correct or not ("test@gmail.com" is type of schema
        // HOW TO DO IT ????
        kafkaEvent.get(field.name()).getClass();
        field.schema().getTypes();
    } else {
        // invalid
    }
}

What will be the way to check if this value is one of the type that defined in schema.

标签: javaavro

解决方案


您应该尝试一些 Avro 序列化程序,例如 Confluent 库,以使用您的模式序列化有效负载。如果库无法使用模式序列化/验证有效负载,它将引发异常。


推荐阅读