扁平缓冲区 - 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对象来读取默认值。
广告