Flat Buffers - JSON to Binary



Overview

JSON is very popular data transfer format over the network. In order to provide JSON compatability, Flat Buffers complier flatc has option to convert a source JSON to flat buffer binary format which can then be used to deserialize objects represented originally by JSON.

Consider the following JSON carrying a Theater object information

theater.json

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

theater.fbs

This is our Flat Buffers Schema file

namespace com.tutorialspoint.theater;

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

Now let's first get the flat buffer binary representation of json (theater.json) as per our schema (theater.fbs) using below command.

flatc --binary theater.fbs theater.json

It will create theater.bin in the current folder which we can read to deserialize the Theater object.

Creating Java Classes from fbs File

To use FlatBuffers, we will now have to use flatc binary to create the required classes from this ".fbs" file. Let us see how to do that −

flatc  --java theater.fbs

This will create a Theater class in com > tutorialspoint > theater folder in current directory. We're using this class in our application similar to as done in Flat Buffers - Schema chapter.

Using Java Class created from fbs File

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());        
      }
   }
}

Compile the project

Now that we have set up the reader and the writer, let us compile the project.

mvn clean install

Deserialize the Serialized Object

Now, let us execute the reader to read from the same file −

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

So, as we see, we are able to read the default values by deserializing the binary data to the Theater object.

Advertisements