3

hi stackoverflow community :)

i want create a flatbuffers object in java which i can serialize to a byte array, and later deserialize back in the java object. i work the first time with flatbuffers and i can't initialised a java object. my way step by step:

  1. write a scheme
  2. compile this with the flatbuffers compiler into a java class
  3. import the flatbuffers class from github
  4. try to build a java object

Here is my code for step 4:

FlatBufferBuilder fbb = new FlatBufferBuilder(1);
int str = fbb.createString("Dummy");
Monster.startPerson(fbb);
Monster.addName(fbb, str);
int p = Person.endPerson(fbb);

Maybe someone can post a simple example to creating a flatbuffers object, and how to serialize and deserialize to and from bytearray?

Hope for an answer and best regards,

Paul

http://google.github.io/flatbuffers/

Rhumborl
  • 16,349
  • 4
  • 39
  • 45
Pa Rö
  • 449
  • 1
  • 6
  • 18

3 Answers3

5

a answer on the google group page: https://groups.google.com/forum/#!topic/flatbuffers/FZBDMd9m0hE

Pa Rö
  • 449
  • 1
  • 6
  • 18
  • How would you de-serialize it from byte array to FlatBuffer. Answer on this page doesn't cover de-serializing case. – Tariq Oct 05 '15 at 14:09
2

Serialize

FlatBufferBuilder fbb = new FlatBufferBuilder();
int str = fbb.createString("MyMonster");
Monster.startMonster(fbb);
Monster.addName(fbb, str);
int mon = Monster.endMonster(fbb); 
fbb.finish(mon);   
byte[] data = fbb.sizedByteArray();

Deserialzie

ByteBuffer buff = ByteBuffer.wrap(data);
Monstermonster monster = Monster.getRootAsMonster(buff);
System.out.println(monster.name());

Hope this help.

MashiMaro
  • 39
  • 7
2

Consider you have the following FlatBuffers schema:

table ServiceException {
    message:string;
}

After compiling this schema with flatc to generate Java classes, you can create a ServiceException instance and convert it into a byte[] as follows:

FlatBufferBuilder fbb = new FlatBufferBuilder();
int messagePosition = fbb.createString("something bad happened");
int serviceExceptionPosition = ServiceException.createServiceException(fbb, messagePosition);
fbb.finish(serviceExceptionPosition);
byte[] outputBytes = fbb.sizedByteArray();

Next, you convert the generated outputBytes back into a ServiceException instance:

ByteBuffer inputByteBuffer = ByteBuffer.wrap(outputBytes);
ServiceException serviceException = ServiceException.getRootAsServiceException(inputByteBuffer);
Volkan Yazıcı
  • 1,530
  • 1
  • 15
  • 28