2016-07-28 20 views
5

我正在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数组中。

回答

1

我认为你的代码有两个错误,但我不熟悉Avro,所以我不能保证其中的一个。我只是很快你链接的文档偷看这里就是我理解avro_value_append

创建一个新的元素,即教师和回报是通过在第二个参数中引用(所以它返回按引用)。我的猜测是,您需要使用其他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容器将从其脚下擦掉数据。

相关问题