我正在用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
  }
]
}

在我的Objective-C代码中,我有一个Teacher对象数组,每个教师对象都包含nameage的值。

我想使用上面显示的架构使用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数组中。

最佳答案

我认为您的代码有两个问题,但是我对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

我不确定您是否正确设置了员工,顺便说一句,我没有时间对此进行研究。

第二个问题将在某些时候与您的name用法有关。我假设Avro期望使用C字符串,但是您在此处使用的是NSString。您必须在其上使用getCString:maxLength:encoding:方法来填充准备好的缓冲区,以创建可在Avro中传递的C字符串。您可能还可以使用UTF8String,但请阅读其文档:您可能必须复制内存(memcpy shenanigans),否则您的Avro容器会将其数据从脚下擦掉。

关于ios - 使用C语言将数组数据设置为Avro数组类型,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38639352/

10-13 00:25