我可以将平面缓冲区序列化/从JSON序列化/反序列化吗?

Zif*_*ion 5 c++ serialization json deserialization flatbuffers

是否可以在JSON中对平面缓冲区进行序列化/反序列化?

我真正想做的是将平面缓冲区保存为JSON,允许人们更改所需的任何值,然后将JSON读回平面缓冲区(并在应用程序中以某种方式使用)。

也许还有另一种方法可以达到相同的效果。我们正在使用C ++。

vk-*_*ode 7

这就是我用的

包含平面缓冲区架构的sample.fbs 文件。

table sample
{
    firstName: string;
    lastName: string;
    age: int;
}

root_type sample;
Run Code Online (Sandbox Code Playgroud)

将 JSON 解析为 Flatbuffers 二进制并返回 JSON 的程序

#include <iostream>
#include <string>

#include "flatbuffers/idl.h"

int main()
{
    std::string input_json_data = "{ \
            firstName: \"somename\", \
            lastName: \"someothername\", \
            age: 21 \
        } \
        ";

    std::string schemafile;
    std::string jsonfile;
    bool ok = flatbuffers::LoadFile("sample.fbs", false, &schemafile);
    if (!ok) {
        std::cout << "load file failed!" << std::endl;
        return -1;
    }

    flatbuffers::Parser parser;
    parser.Parse(schemafile.c_str());
    if (!parser.Parse(input_json_data.c_str())) {
        std::cout << "flatbuffers parser failed with error : " << parser.error_ << std::endl;
        return -1;
    }

    std::string jsongen;
    if (!GenerateText(parser, parser.builder_.GetBufferPointer(), &jsongen)) {
        std::cout << "Couldn't serialize parsed data to JSON!" << std::endl;
        return -1;
    }

    std::cout << "intput json" << std::endl
              << input_json_data << std::endl
              << std::endl
              << "output json" << std::endl
              << jsongen << std::endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

产生以下输出

$ ./build/output/test_json_fb 
intput json
{             firstName: "somename",             lastName: "someothername",             age: 21         }         

output json
{
  firstName: "somename",
  lastName: "someothername",
  age: 21
}
Run Code Online (Sandbox Code Playgroud)

通过引用页面创建https://github.com/google/flatbuffers/blob/master/samples/sample_text.cpp


Aar*_*pel 5

是的,这是FlatBuffers中的内置功能。请参阅“文本和模式解析”在这里:https://google.github.io/flatbuffers/flatbuffers_guide_use_cpp.html 也看到这样的例子test.cppParseAndGenerateTextTest(),或者还registry.h