avro union的json编码

eng*_*007 5 java json avro

我的 avro 模式中有一个 favorite_number 的联合,它可以是 null 或 int。当我对对象进行 json 编码时,我得到:

{“name”:“Alyssa”,“favorite_number”:{“int”:7},“favorite_color”:null}

我试图摆脱联合的类型指示符,在本例中是 int,以便它变成:

{"name": "Alyssa", "favorite_number": 7, "favorite_color": "blue"}

avro 架构:

{"name": "person", "type": "record",
           "fields": [
              {"name": "name", "type": "string"},
              {"name": "favorite_number", "type": ["null", "int"], "default": null},
              {"name": "favorite_color", "type": "string"}
           ]
   }
Run Code Online (Sandbox Code Playgroud)

有没有办法做到这一点?谢谢!

hla*_*gos 4

编辑整个答案:)

看起来不可能直接使用 Avro API 来完成此操作。有一个拉取请求待处理一段时间以支持可空类型

https://issues.apache.org/jira/browse/AVRO-1582

编辑:

根据您的评论,我发现尝试在没有数据类型的情况下序列化同样的问题,我最终使用了https://avro.apache.org/docs/1.8.1/api/java/org/apache/avro中定义的 toString 函数/generic/GenericData.html#toString(java.lang.Object),它无法正常工作的唯一情况是对于具有循环引用的模式。