Flat Buffers - 二进制到 JSON

概述

JSON 是一种非常流行的网络数据传输格式。为了提供 JSON 兼容性,Flat Buffers 编译器 flatc 可以选择将源 JSON 转换为Flat Buffers二进制格式,然后可以使用该格式反序列化最初由 JSON 表示的对象。我们在上一章Flat Buffers - JSON 到二进制中已经练习过这一点。现在我们将执行反转,从 Flat Buffers 二进制文件中检索 JSON。

考虑上一章 Flat Buffers - JSON to Binary 中创建的 theater.bin 文件。

以下是 flat buffers 编译器正确解释二进制数据所需的模式。

theater.fbs

namespace com.tutorialspoint.theater;

table Theater {
   name:string;
   address:string;
   mobile:int;
}
root_type Theater;

生成 JSON

现在让我们首先使用以下命令从二进制文件 (theater.bin) 中获取所需的 json (theater.json)。

flatc --json --raw-binary theater.fbs -- theater.bin

它将在当前文件夹中创建 theater.json,如下所示。


{
   name: "Silver Screener",
   address: "212, Maple Street, LA, California",
   mobile: 12322224
}

严格模式

flatc 生成最小 json。如果我们需要使用其他工具处理 JSON,并且需要正确的引用标识符,那么我们可以使用 --strict-json,如下所示:

flatc --json --raw-binary theater.fbs -- theater.bin --strict-json

它将在当前文件夹中创建 theater.json,如下所示。


{
   "name": "Silver Screener",
   "address": "212, Maple Street, LA, California",
   "mobile": 12322224
}

默认值

默认情况下,flatc 编译器会忽略默认值,默认值不会以二进制表示形式存储。因此这些值也不会以 JSON 形式出现。为了实现这一点,我们可以使用 --defaults-json 选项,如下例所示。

让我们将 mobile 值保留为 json 中的默认值。

theater.json


{
   "name" : "Silver Screener",
   "address" : "212, Maple Street, LA, California",
   "mobile": 0
}

现在让我们首先使用以下命令根据我们的模式 (theater.fbs) 获取 json 的Flat Buffers二进制表示 (theater.json)。

flatc --binary theater.fbs theater.json

生成没有默认值的 JSON

现在让我们首先使用以下命令从我们的二进制文件 (theater.bin) 获取所需的 json (theater.json)。

flatc --json --raw-binary theater.fbs -- theater.bin

它将在当前文件夹中创建 theater.json,如下所示。


{
   name: "Silver Screener",
   address: "212, Maple Street, LA, California"
}

使用默认值生成 JSON

现在使用 --defaults-json 选项生成 JSON。

flatc --json --raw-binary theater.fbs -- theater.bin --defaults-json

它将在当前文件夹中创建 theater.json,如下所示。


{
   name: "Silver Screener",
   address: "212, Maple Street, LA, California",
   mobile: 0
}