请看下面的代码,它设置了 union 分支和 int 分支:
注意:对于union,需要在设置数据前设置相关分支。联合分支索引从 0 开始,称为判别式。对于此示例中的 int 字段,判别式为 0(因为它是第一个字段)。对于空分支,判别式为 1(因为它是第二个字段)。将 null 作为第一个分支更为常见,但是,我遵循了您的问题示例。
#include "avro.h"
void main()
{
const char schema_json[] =
"{ \"type\":\"record\", \"name\":\"foo\","
"\"fields\": ["
"{ \"name\": \"nullableint\", \"type\":[\"int\",\"null\"]}"
"]}";
avro_schema_t my_schema;
avro_schema_from_json( schema_json, 0, &my_schema, NULL );
avro_datum_t my_record = avro_datum_from_schema( my_schema );
avro_datum_t my_int_field = NULL;
avro_datum_t branch = NULL;
char *json = NULL;
//get the int field
avro_record_get( my_record, "nullableint", &my_int_field );
//set the int branch on this field
avro_union_set_discriminant( my_int_field, 0, &branch );
//set value of 100 at this int branch
avro_int32_set( branch, 100 );
//convert the datum record data to json
avro_datum_to_json( my_record, 1, &json );
printf( "got json for int branch: %s\n", json );
//get the int field
avro_record_get( my_record, "nullableint", &my_int_field );
//set the null branch on this field
avro_union_set_discriminant( my_int_field, 1, &branch );
//convert the datum record data to json
avro_datum_to_json( my_record, 1, &json );
printf( "got json for null branch: %s\n", json );
}
我将数据打印为 json 以便更好地检查结果。这个程序的输出是
got json for int branch: {"nullableint": {"int": 100}}
got json for null branch: {"nullableint": null}
顺便说一句,约定是将空分支作为第一个分支,具有
"{ \"name\": \"nullableint\", \"type\":[\"null\",\"int\"]}"
而不是
"{ \"name\": \"nullableint\", \"type\":[\"int\",\"null\"]}"
请参阅 avro 规范中的引用:https://avro.apache.org/docs/1.8.2/spec.html
(请注意,当为类型为联合的记录字段指定默认值时,默认值的类型必须与联合的第一个元素匹配。因此,对于包含“null”的联合,“null”通常首先列出,因为此类联合的默认值通常为 null。)