Java中的Avro枚举序列化

时间:2020-04-23 06:44:00

标签: java enums avro confluent-schema-registry

我正在尝试将枚举值序列化为Avro消息并将其发送。 该架构使用以下内容构建:

Schema myschema = SchemaBuilder.record("com.testing.schemas").fields()
.name("enumTest").type().nullable().enumeration("aname")
.symbols("a","b","c","d","e").noDefault();

看起来像这样

{"name":"enumTest","type":
[{"type":"enum","name":"aname",
"symbols":"a","b","c","d","e"]}
,"null"]}

我的代码:

GenericRecord record = new GenericData.Record(myschema);
GenericData.EnumSymbol symbol = new GenericData.EnumSymbol(
myschema.getField("enumTest").schema(), "a");
record.put("enumTest", symbol);

尝试发送消息时出现错误:

Error serializing Avro message
org.apache.avro.UnresolvedUnionException: Not in union [{"type":"enum","name":"aname","namespace":"com.testing.schemas","symbols":["a","b","c","d","e"]},"null"]: a

我想念什么? 谢谢。

1 个答案:

答案 0 :(得分:0)

字段aname的类型是联合,而不是枚举:

[ {
  "type" : "enum",
  "name" : "aname",
  "namespace" : "com.testing",
  "symbols" : [ "a", "b", "c", "d", "e" ]
}, "null" ]

您可以执行以下操作:

    String namespace = "com.testing";

    Schema enumTest =
        SchemaBuilder.enumeration("aname")
            .namespace(namespace)
            .symbols("a", "b", "c", "d", "e");

    Schema myschema =
        SchemaBuilder.record("schemas")
            .namespace(namespace)
            .fields()
            .name("enumTest")
            .type()
            .unionOf()
            .nullType()
            .and()
            .type(enumTest)
            .endUnion()
            .noDefault()
            .endRecord();

    GenericRecord record = new GenericData.Record(myschema);
    GenericData.EnumSymbol symbol = new GenericData.EnumSymbol(enumTest, "a");
    record.put("enumTest", symbol);