模式:
const char schema[] =
"{ \"type\":\"record\", \"name\":\"foo\","
"\"fields\": ["
"{ \"name\": \"nullableint\", \"type\":[\"int\",\"null\"]}"
"]}";
设置架构:
avro_datum_t foo_record = avro_record(schema);
设置可为空的原点:
avro_datum_t nullableint = avro_int32(1);
设置项目:
int err = avro_record_set(foo_record,"nullableint",nullableint);
写项目:
int err2 = avro_file_writer_append(avro_writer, foo_record);
并且有一个错误。不知何故,我必须设置可为空的条目的分支,但是我看不到任何函数可以做到这一点。
如何将此值设置为null
或int?
答案 0 :(得分:0)
请参见以下代码,该代码设置并集分支和int分支:
注意:对于联合,您需要在设置数据之前设置相关分支。联合分支索引从0开始,称为判别式。对于本例中的int字段,判别式为0(因为它是第一个字段)。对于null分支,判别式为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。)