[英]Avro Enum Serialization in Java
I am trying to serialize an enum value into an Avro message and send it.我正在尝试将枚举值序列化为 Avro 消息并发送它。 The schema is built with:架构是用以下内容构建的:
Schema myschema = SchemaBuilder.record("com.testing.schemas").fields()
.name("enumTest").type().nullable().enumeration("aname")
.symbols("a","b","c","d","e").noDefault();
and looks like this看起来像这样
{"name":"enumTest","type":
[{"type":"enum","name":"aname",
"symbols":"a","b","c","d","e"]}
,"null"]}
My code:我的代码:
GenericRecord record = new GenericData.Record(myschema);
GenericData.EnumSymbol symbol = new GenericData.EnumSymbol(
myschema.getField("enumTest").schema(), "a");
record.put("enumTest", symbol);
When trying to send the message I get the error:尝试发送消息时出现错误:
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
What am I missing?我错过了什么? Thanks.谢谢。
The type of field aname
is a Union, not an Enum:字段aname
的类型是 Union,而不是 Enum:
[ {
"type" : "enum",
"name" : "aname",
"namespace" : "com.testing",
"symbols" : [ "a", "b", "c", "d", "e" ]
}, "null" ]
You could do something like this:你可以这样做:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.