
- Flat Buffers - Home
- Flat Buffers - Introduction
- Flat Buffers - Environment Setup
- Flat Buffers - Schema
- Flat Buffers - Constructs
- Flat Buffers - table
- Flat Buffers - string
- Flat Buffers - Numbers
- Flat Buffers - Boolean
- Flat Buffers - Enum
- Flat Buffers - Vector
- Flat Buffers - Struct
- Flat Buffers - Union
- Flat Buffers - Nested Table
- Flat Buffers - Default Values
- Flat Buffers - JSON to Binary
- Flat Buffers - Binary to JSON
- Flat Buffers - Mutatable Buffers
- Flat Buffers - Backward Compatability
- Flat Buffers - Language Independence
- Flat Buffers Useful Resources
- Flat Buffers - Quick Guide
- Flat Buffers - Useful Resources
- Flat Buffers - Discussion
Flat Buffers - union
Overview
The union data type is one of the composite datatypes of Flat Buffers. It is used to create a flexible data struture which can take any of the required type.
Continuing with our theater example from Flat Buffers - String chapter, following is the syntax that we need to have to instruct FlatBuffers that we will be creating a union −
theater.fbs
namespace com.tutorialspoint.theater; union People { Employee, Viewer } table Theater { people: People; } table Employee { name:string; address:string; id: int; } table Viewer { name: string; address: string; } root_type Theater;
Now our table contains union attribute defined as People of two tables Employee and Viewer. In Theater table, we've defined people of our union type which means which we can store any of the Employee or Viewer in people variable.
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 Theater, People, Employee and Viewer classes 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 Classes created from fbs File
Creating and Writing Union
In order to create a Union, we need to first prepare the offset of required type, for example Viewer and then we can add the viewer along with its type to the flat buffer.
// create offset for Viewer int viewerName = builder.createString("Mery"); int viewerAddress = builder.createString("Avenue 4"); int viewer = Viewer.createViewer(builder, viewerName, viewerAddress); //add union tyoe Theater.addPeopleType(builder, People.Viewer); // add details to the Theater FlatBuffer Theater.addPeople(builder, viewer);
Following example code is showing the process of creating a Union.
TheaterWriter.java
package com.tutorialspoint.theater; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import com.google.flatbuffers.FlatBufferBuilder; public class TheaterWriter { public static void main(String[] args) throws FileNotFoundException, IOException { // create a flat buffer builder // it will be used to create Theater FlatBuffer FlatBufferBuilder builder = new FlatBufferBuilder(1024); // create offset for Viewer int viewerName = builder.createString("Mery"); int viewerAddress = builder.createString("Avenue 4"); int viewer = Viewer.createViewer(builder, viewerName, viewerAddress); // create offset for vector //int people = Theater.createPeople // create theater FlatBuffers using startTheater() method Theater.startTheater(builder); //add union type Theater.addPeopleType(builder, People.Viewer); // add details to the Theater FlatBuffer Theater.addPeople(builder, viewer); // mark end of data being entered in Greet FlatBuffer int theater = Theater.endTheater(builder); // finish the builder builder.finish(theater); // get the bytes to be stored byte[] data = builder.sizedByteArray(); String filename = "theater_flatbuffers_output"; System.out.println("Saving theater to file: " + filename); // write the builder content to the file named theater_flatbuffers_output try(FileOutputStream output = new FileOutputStream(filename)){ output.write(data); } System.out.println("Saved theater with following data to disk: \n" + theater); } }
Reading Union
In order to read a Union, we can check the type of the union object and then retrieve values accordingly..
// get the saved union type int unionType = theater.peopleType(); // if union is of type Viewer if(unionType == People.Viewer) { Viewer viewer = (Viewer)theater.people(new Viewer()); System.out.println("Name: " + viewer.name()); System.out.println("Address: " + viewer.address()); } // if union is of type Employee else if(unionType == People.Employee) { Employee employee = (Employee)theater.people(new Employee()); System.out.println("Name: " + employee.name()); System.out.println("Address: " + employee.address()); System.out.println("Id: " + employee.id()); }
Following example code is showing the process of reading a Union.
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_flatbuffers_output"; 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("People: "); // get the type of union int unionType = theater.peopleType(); // if union is of Viewer type if(unionType == People.Viewer) { Viewer viewer = (Viewer)theater.people(new Viewer()); System.out.println("Name: " + viewer.name()); System.out.println("Address: " + viewer.address()); } else if(unionType == People.Employee) { Employee employee = (Employee)theater.people(new Employee()); System.out.println("Name: " + employee.name()); System.out.println("Address: " + employee.address()); System.out.println("Id: " + employee.id()); } } } }
Compile the project
Now that we have set up the reader and the writer, let us compile the project.
mvn clean install
Serialize the Java Object
Now, post compilation, let us execute the writer first −
> java -cp .\target\flatbuffers-tutorial-1.0.jar com.tutorialspoint.theater.TheaterWriter Saving theater information to file: theater_flatbuffers_output Saved theater information with following data to disk: 60
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_flatbuffers_output People: Name: Mery Address: Avenue 4
So, as we see, we are able to read the serialized struct by deserializing the binary data to Theater object. In the next chapter Flat Buffers - Nested Tables, we will look at the Nested Tables, a composite type.