Flatbuffer和JSON之间相互转换详细教程

发布于:2023-01-21 ⋅ 阅读:(342) ⋅ 点赞:(0)

准备

下载 flatc文件

Release FlatBuffers release 2.0.0 · google/flatbuffers · GitHubFlatBuffers: Memory Efficient Serialization Library - Release FlatBuffers release 2.0.0 · google/flatbuffershttps://github.com/google/flatbuffers/releases/tag/v2.0.0

要保证Flatbuffer文件中的格式和JSON数据文件格式是一致的

Flatbuffer 结构文件test.fbs内容:

namespace Fltest;

table Car{
    id:int;
    number:long;
    describle:string;
}
table Person{
    id:int;
    name:string;
    code:long;
    isVip:bool;
    carList:[Car];
}
table RootType{
    items:[Person];
    stateid:int;
    time:long;

}

root_type RootType;

JSON格式数据test.json的内容:

{
    "items": [{
        "id": 1001,
        "name": "张三",
        "code": 1222,
        "carList": [{
            "id": 10001,
            "number": 123456321,
            "describle": "这是张三第一辆车"
        }]

    }, {
        "id": 1002,
        "name": "李四",
        "code": 1123,
        "carList": [{
            "id": 10001,
            "number": 123456001,
            "describle": "这是李四第一辆车"
        }, {
            "id": 10002,
            "number": 123456002,
            "describle": "这是李四第二辆车"
        }, {
            "id": 10003,
            "number": 123456003,
            "describle": "这是李四第三辆车"
        }]

    }],
    "stateid":404,
    "time":20161127
}

文件列表:

序列化

JSON数据序列化为Flatbuffers数据,根据json文件和fbs文件序列化可传输的二进制数据,会生成一个test.bin的二进制文件,并且会生成java文件。

flatc -j -b ./test.fbs ./test.json

运行之后会生成bin文件

反序列化 

此时删除test.json文件,通过反序列化生成.json文件

 

Flatbuffer数据反序列化为JSON文件,根据上面生成的bin文件和fbs文件转成JSON数据文件。文件名叫test.json

flatc.exe --raw-binary -t ./test.fbs -- ./test.bin

运行命令后会生成test.json文件

 查看反序列化后的内容