Flat Buffers - Binary to JSON



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. This we've exercised in our previous chapter Flat Buffers - JSON to Binary. Now we'll perform the reversal where we'll retrive the JSON from Flat Buffers Binary file.

Consider the theater.bin file created in previous chapter Flat Buffers - JSON to Binary.

Following is the our schema which is required for flat buffers compiler to correctly interpret the binary data.

theater.fbs

namespace com.tutorialspoint.theater;

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

Generate JSON

Now let's first get the required json (theater.json) from our binary (theater.bin) using below command.

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

It will create theater.json in the current folder as follows.

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

Strict Mode

flatc generates minimal json. In case, we need to process JSON with other tools and proper quoted identifiers are required then we can use --strict-json as shown below:

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

It will create theater.json in the current folder as follows.

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

Default Values

By default, flatc compiler ignores default values and default values are not stored in binary representation. Thus those values will not come in JSON as well. In order to achieve this, we can use --defaults-json option as shown in below example.

Let's keep mobile value as default in json.

theater.json

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

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

Generate JSON without default

Now let's first get the required json (theater.json) from our binary (theater.bin) using below command.

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

It will create theater.json in the current folder as follows.

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

Generate JSON with default

Now generate the JSON with --defaults-json option.

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

It will create theater.json in the current folder as follows.

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