我正在使用这个 Avro 架构:
价格-state.avsc
{
"namespace": "com.company.model",
"name": "Product",
"type": "record",
"fields": [
{
"name": "product_id",
"type": "string"
},
{
"name": "sale_prices",
"type": {
"name": "sale_prices",
"type": "record",
"fields": [
{
"name": "default",
"type": {
"name": "default",
"type": "record",
"fields": [
{
"name": "order_by_item_price_by_item",
"type": [
"null",
{
"name": "markup_strategy",
"type": "record",
"fields": [
{
"name": "type",
"type": {
"name": "type",
"type": "enum",
"symbols": ["margin", "sale_price"]
}
}
]
}
]
},
{"name": "order_by_item_price_by_weight", "type": ["null", "string"]},
{"name": "order_by_weight_price_by_weight", "type": ["null", "string"]}
]
}
}
]
}
}
]
}
它在 this website 上正确验证所以我假设模式是有效的。
我在构建一个 JSON 文件时遇到问题,然后应该使用上述模式进行编码。
我正在使用这个 JSON 进行一些测试:
test.json
{
"product_id": "123",
"sale_prices": {
"default": {
"order_by_item_price_by_item": {
"markup_strategy": {
"type": {"enum": "margin"}
}
},
"order_by_item_price_by_weight": null,
"order_by_weight_price_by_weight": null
}
}
}
运行时
java -jar avro-tools-1.8.2.jar fromjson --schema-file prices-state.avsc test.json
我得到:Exception in thread "main" org.apache.avro.AvroTypeException: Unknown union branch markup_strategy
我读了 here由于 JSON 编码,我必须将东西包装在联合中,所以我尝试了不同的组合,但似乎没有一个可以工作。
最佳答案
这是一个 命名空间 分辨率问题。以这个简化的模式为例:
test.avsc
{
"name": "Product",
"type": "record",
"fields": [
{
"name": "order_by_item_price_by_item",
"type": [
"null",
{
"type": "record",
"name": "markup_strategy",
"fields": [{
"name": "type",
"type": {
"name": "type",
"type": "enum",
"symbols": ["margin", "sale_price"]
}
}]
}
]
}
]
}
使用以下 JSON,它可以很好地验证
test.json
{
"order_by_item_price_by_item": {
"markup_strategy": {
"type": "margin"
}
}
}
现在,如果您要在架构之上添加一个命名空间,例如
test.avsc
{
"namespace": "test",
"name": "Product",
"type": "record",
"fields": [
...
那么你需要改变你的 test.json 或者你会得到
Exception in thread "main" org.apache.avro.AvroTypeException: Unknown union branch markup_strategy
final_test.json
{
"order_by_item_price_by_item": {
"test.markup_strategy": {
"type": "margin"
}
}
}
因此,当在联合类型中并且您对 Avro 的命名类型(记录、固定或枚举)进行 JSON 编码时,其中使用了用户指定的名称,那么该类型的名称也需要在名称前面加上命名空间名称以进行解析。
更多关于 namespaces和 JSON encoding .
关于avro - org.apache.avro.AvroTypeException : Unknown union branch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49926146/