2016-07-28 21 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容器將從其腳下擦掉數據。

相關問題