使用Flat C版本(FlatCC)很容易將flatbuffer緩衝區轉換爲JSON。
請參考flatcc源路徑中的示例測試:flatcc-master/test/json_test。
使用生成所需的JSON助手頭的文件
flatcc_d -a --json <yourData.fbs>
它會生成yourData_json_printer.h。將此頭文件包含在您的程序中。
修改以下代碼以適應<yourData>
。緩衝區是從另一端收到的flatbuffer輸入。 也不要使用sizeof()從flatbuffer的buffer中獲取bufferSize。調用此函數 前打印緩衝區大小
void flatbufToJson(const char *buffer, size_t bufferSize) {
flatcc_json_printer_t ctx_obj, *ctx;
FILE *fp = 0;
const char *target_filename = "yourData.json";
ctx = &ctx_obj;
fp = fopen(target_filename, "wb");
if (!fp) {
fprintf(stderr, "%s: could not open output file\n", target_filename);
printf("ctx not ready for clenaup, so exit directly\n");
return;
}
flatcc_json_printer_init(ctx, fp);
flatcc_json_printer_set_force_default(ctx, 1);
/* Uses same formatting as golden reference file. */
flatcc_json_printer_set_nonstrict(ctx);
//Check and modify here...
//the following should be re-written based on your fbs file and generated header file.
<yourData>_print_json(ctx, buffer, bufferSize);
flatcc_json_printer_flush(ctx);
if (flatcc_json_printer_get_error(ctx)) {
printf("could not print data\n");
}
fclose(fp);
printf("######### Json is done: \n");
}