2

I have a 3-level nested Java POJO that looks like this in the schema file:

struct FPathSegment {
    originIata:ushort;
    destinationIata:ushort;
}

table FPathConnection {
    segments:[FPathSegment]; 
}   

table FPath {
    connections:[FPathConnection];
}

When I try to serialize a Java POJO to the Flatbuffer equivalent I pretty much get "nested serialzation is not allowed" error every time I try to use a common FlatBufferBuilder to build this entire object graph.

There is no clue in the docs to state if I have a single builder for the entire graph? A separate one for every table/struct? If separate, how do you import the child objects into the parent?

There are all these methods like create/start/add various vectors, but no explanation what builders go in there. Painfully complicated.

Here is my Java code where I attempt to serialize my Java POJO into Flatbuffers equivalent:

private FPath convert(Path path) {
    FlatBufferBuilder bld = new FlatBufferBuilder(1024);

    // build the Flatbuffer object
    FPath.startFPath(bld);
    FPath.startConnectionsVector(bld, path.getConnections().size());

    for(Path.PathConnection connection : path.getConnections()) {

        FPathConnection.startFPathConnection(bld);

        for(Path.PathSegment segment : connection.getSegments()) {
            FPathSegment.createFPathSegment(bld,
                    stringCache.getPointer(segment.getOriginIata()),
                    stringCache.getPointer(segment.getDestinationIata()));
        }

        FPathConnection.endFPathConnection(bld);
    }

    FPath.endFPath(bld);
    return FPath.getRootAsFPath(bld.dataBuffer());
}

Every start() method throws a "FlatBuffers: object serialization must not be nested" exception, can't figure out what is the way to do this.

Jacek Furmankiewicz
  • 1,143
  • 1
  • 13
  • 22

1 Answers1

3

You use a single FlatBufferBuilder, but you must finish serializing children before starting the parents.

In your case, that requires you to move FPath.startFPath to the end, and FPath.startConnectionsVector to just before that. This means you need to store the offsets for each FPathConnection in a temp array.

This will make the nesting error go away.

The reason for this inconvenience is to allow the serialization process to proceed without any temporary data structures.

Aardappel
  • 5,559
  • 1
  • 19
  • 22