我正在Objective-C中編程。我正在使用Apache Avro進行數據序列化。將arrary數據設置爲使用C語言的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
}
]
}
在我的Objective-C代碼,我有Teacher
對象的數組,每個老師對象包含name
& age
值。
我想用上面顯示的模式使用Avro將教師數組數據寫入文件。我主要關心如何將數據寫入上述模式中定義的Employees
數組。
這裏是我的代碼(我用C代碼風格做到這一點,我按照Avro C documentation):
// 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 ++;
}
我想問的問題,實際上是在上面的代碼註釋。
我遵循Avro C文檔,但我迷路了我怎麼能把每個teacher
加到employees
?在我上面的代碼中,我只將每個老師的name
添加到employees
數組中。