Apache Avro:使用union数据类型时UnresolvedUnionException

时间:2013-12-02 16:44:46

标签: java apache avro

我正在使用Apache Avro进行对象序列化。

我有一个School对象的Avro架构:

{"namespace": "com.my.model",
 "type": "record",
 "name": "School",
 "fields": [
     {"name": "sid",  "type": "int"},
     {"name": "size",  "type": "long"},
     {"name": "other", "type": ["null", "Teacher", "Student"]}
   ]
}

如上所示,"other"字段包含联合数据类型,可以是nullTeacher实例,也可以是{{1实例。

教师对象架构:

Student

学生对象架构:

{"namespace": "com.my.model",
"type": "record",
"name": "Teacher",
    "fields": [
        {"name": "isMale", "type": "boolean"}
    ]
}

我用Avro工具&编译了上面的模式。 Avro自动为我生成了所有Java类。

然后,在我的java程序中,我按以下方式创建{"namespace": "com.my.model", "type": "record", "name": "Student", "fields": [ {"name": "age", "type": "int"} ] } 实例:

School

如上所示,学校实例的School school = new School(); school.setSid(3); school.setSize(2000); //create a student object Student student = new Student(); student.setAge(18); //set student into school instance school.setOther(student); 字段包含学生对象。当我编译我的代码时,我得到了 UnresolvedUnionException 。它抱怨other架构的other字段的联合数据类型。似乎无法解析我在Java代码中设置为School的{​​{1}}。为什么这个例外? Stacktrace是:

student

1 个答案:

答案 0 :(得分:0)

我可能会弄错,但我认为Union类型应该只包含一个非默认值:

{
    "name": "other",
    "type": [
        "null",
        "Teacher",
        "Student"
    ]
}

应该是:

{
    "name": "other",
    "type": [
        "null",
        {
            "name": "Visitors",
            "symbols": [
                "Student",
                "Teacher"
            ],
            "type": "enum"
        }
    ]
}