2017-02-03 30 views
0

FlatBuffer允許將二進制fbs文件轉換爲JSON或從JSON轉換(當然架構將是已知的)?將FlatBuffer轉換爲來自各種語言的JSON

我的想法是在FlatBuffer中定義管道的結構模式&過濾器體系結構。 FlatBuffer文件也將在管道之間交換。但是,某些過濾器中的某些工具會要求我傳遞從FlatBuffer文件轉換而來的普通舊json對象。我有幾種語言可以支持(C++,Python,Java,JS)。

我發現這似乎做一個JavaScript庫: https://github.com/evanw/node-flatbuffers/

但似乎abdondened,我在官方支持的方式相當感興趣。

回答

1

只有C++開箱即可提供此功能。

對於其他語言,您可以包裝C++分析器/生成器並調用它(請參閱(例如)參見Java:http://frogermcs.github.io/json-parsing-with-flatbuffers-in-android/)。

@evanw是FlatBuffers中JS端口的原作者,所以你提到的這個項目可能是可用的,但我不認爲他正在積極維護它。

或者,如果它在服務器上運行並且可以運行命令行實用程序,則可以使用flatc二進制文件通過文件爲您執行轉換。

理想情況下,所有的語言都會有自己的本地語法分析器,但這需要複製很多工作。雖然與C/C++接口是一件痛苦的事情,但它的優勢在於爲您提供了一個非常快速的解析器。

0

使用Flat C版本(FlatCC)很容易將flatbuffer緩衝區轉換爲JSON。

請參考flatcc源路徑中的示例測試:flatcc-master/test/json_test。

  1. 使用生成所需的JSON助手頭的文件

    flatcc_d -a --json <yourData.fbs> 
    
  2. 它會生成yourData_json_printer.h。將此頭文件包含在您的程序中。

  3. 修改以下代碼以適應<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"); 
    
    } 
    
相關問題