扁平緩衝區 - JSON 到二進位制
概述
JSON 是一種非常流行的網路資料傳輸格式。為了提供 JSON 相容性,Flat Buffers 編譯器 flatc 具有將源 JSON 轉換為扁平緩衝區二進位制格式的選項,然後可以使用該格式反序列化最初由 JSON 表示的物件。
考慮以下包含劇院物件資訊的 JSON
theater.json
{
"name" : "Silver Screener",
"address" : "212, Maple Street, LA, California",
"mobile": 12322224
}
theater.fbs
這是我們的 Flat Buffers 模式檔案
namespace com.tutorialspoint.theater;
table Theater {
name:string;
address:string;
mobile:int;
}
root_type Theater;
現在,讓我們首先根據我們的模式 (theater.fbs) 獲取 json (theater.json) 的扁平緩衝區二進位制表示,使用以下命令。
flatc --binary theater.fbs theater.json
它將在當前資料夾中建立 theater.bin,我們可以讀取它以反序列化劇院物件。
從 fbs 檔案建立 Java 類
要使用 FlatBuffers,我們現在必須使用flatc二進位制檔案從此“.fbs”檔案建立所需的類。讓我們看看如何做到這一點 -
flatc --java theater.fbs
這將在當前目錄中的com > tutorialspoint > theater資料夾中建立一個 Theater 類。我們在應用程式中使用此類,類似於在扁平緩衝區 - 模式章節中所做的那樣。
使用從 fbs 檔案建立的 Java 類
TheaterReader.java
package com.tutorialspoint.theater;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
public class TheaterReader {
public static void main(String[] args) throws FileNotFoundException, IOException {
String filename = "theater.bin";
System.out.println("Reading from file " + filename);
try(FileInputStream input = new FileInputStream(filename)) {
// get the serialized data
byte[] data = input.readAllBytes();
ByteBuffer buf = ByteBuffer.wrap(data);
// read the root object in serialized data
Theater theater = Theater.getRootAsTheater(buf);
// print theater values
System.out.println("Name: " + theater.name());
System.out.println("Address: " + theater.address());
System.out.println("Mobile: " + theater.mobile());
}
}
}
編譯專案
現在我們已經設定了讀取器和寫入器,讓我們編譯專案。
mvn clean install
反序列化序列化物件
現在,讓我們執行讀取器以從同一檔案讀取 -
java -cp .\target\flatbuffers-tutorial-1.0.jar com.tutorialspoint.theater.TheaterReader Reading from file theater.bin Name: Silver Screener Address: 212, Maple Street, LA, California Mobile: 12322224
因此,正如我們所看到的,我們能夠透過將二進位制資料反序列化到Theater物件來讀取預設值。
廣告