FlatBuffers - 二進位制到JSON



概述

JSON 是一種非常流行的網路資料傳輸格式。為了提供 JSON 相容性,FlatBuffers 編譯器 flatc 具有將源 JSON 轉換為 FlatBuffers 二進位制格式的選項,然後可以使用該格式反序列化最初由 JSON 表示的物件。我們在上一章FlatBuffers - JSON 到二進位制中已經實踐了這一點。現在,我們將執行反向操作,從 FlatBuffers 二進位制檔案中檢索 JSON。

考慮上一章FlatBuffers - JSON 到二進位制中建立的 theater.bin 檔案。

以下是 FlatBuffers 編譯器正確解釋二進位制資料所需的模式。

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 (**theater.json**) 的 FlatBuffers 二進位制表示。

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
}
廣告
© . All rights reserved.