Lee*_*fin 5 c schema objective-c ios avro
我在Objective-C编程.我正在使用Apache Avro进行数据序列化.
我的avro架构是这样的:
{
"name": "School",
"type":"record",
"fields":[
{
"name":"Employees",
"type":["null", {"type": "array",
"items":{
"name":"Teacher",
"type":"record",
"fields":[
{"name":"name", "type":"string"}
{"name":"age", "type":"int"}
]
}
}
],
"default":null
}
]
}
Run Code Online (Sandbox Code Playgroud)
在我的Objective-C代码中,我有一个Teacher对象数组,每个教师对象包含name&的值age.
我想使用Avro将教师数组数据写入文件,并显示上面的模式.我主要关注如何将数据写入Employees上述模式中定义的数组.
这是我的代码(我必须使用C样式代码来执行此操作,我遵循Avro C文档):
// I don't show this function, it constructs the a `avro_value_t` based on the schema. No problem here.
avro_value_t school = [self constructSchoolValueForSchema];
// get "Employees" field
avro_value_t employees;
avro_value_get_by_name(school, "employees", &employees, 0);
int idx = 0;
for (Teacher *teacher in teacherArray) {
// get name and age
NSString *name = teacher.name;
int age = teacher.age;
// set value to avro data type.
// here 'unionField' is the field of 'Employees', it is a Avro union type which is either null or an array as defined in schema above
avro_value_t field, unionField;
avro_value_set_branch(&employees, 1, &unionField);
// based on documentation, I should use 'avro_value_append'
avro_value_append(&employees, name, idx);
// I get confused here!!!!
// in above line of code, I append 'name' to 'employees',
//which looks not correct,
// because the 'Employees' array is an array of 'Teacher', not arrary of 'name'
// What is the correct way to add teacher to 'employees' ?
idx ++;
}
Run Code Online (Sandbox Code Playgroud)
我想问的问题实际上是在上面的代码注释中.
我下面说的Avro C文档,但我得到失去了我如何在每个添加teacher到employees?在上面的代码中,我只将每个老师添加name到employees数组中.
我认为你的代码有两处错误,但我对 Avro 不熟悉,所以我不能保证其中之一。我只是快速浏览了您链接的文档,这就是我的理解avro_value_append:
它创建一个新元素,即 Teacher 并通过第二个参数中的引用返回该元素(因此它按引用返回)。我的猜测是,您随后需要使用其他avro...方法来填充该元素(即设置教师的姓名等)。最后,执行以下操作:
avro_value_t teacher;
size_t idx;
avro_value_append(&employees, &teacher, &idx); // note that idx is also returned by reference and now contains the new elements index
Run Code Online (Sandbox Code Playgroud)
我不确定您是否正确设置了员工,顺便说一句,我没有时间调查这一点。
第二个问题会随着你name在某些时候的使用而出现。我假设 Avro 需要 C 字符串,但你NSString在这里使用的是 C 字符串。您必须使用getCString:maxLength:encoding:它的方法来填充准备好的缓冲区,以创建可以在 Avro 中传递的 C 字符串。您或许也可以使用UTF8String,但请阅读其文档:您可能必须复制内存(memcpy恶作剧),否则您的 Avro 容器将使其数据从其脚下消失。
| 归档时间: |
|
| 查看次数: |
464 次 |
| 最近记录: |