我有一个 3 级嵌套的 Java POJO,在架构文件中如下所示:
struct FPathSegment {
originIata:ushort;
destinationIata:ushort;
}
table FPathConnection {
segments:[FPathSegment];
}
table FPath {
connections:[FPathConnection];
}
当我尝试将 Java POJO 序列化为 Flatbuffer 等效项时,每次尝试使用通用 FlatBufferBuilder 构建整个对象图时,我几乎都会收到“不允许嵌套序列化”错误。
文档中没有任何线索说明我是否有整个图表的单个构建器?每个表/结构都有一个单独的?如果是分开的,如何将子对象导入到父对象中?
有所有这些方法,例如创建/启动/添加各种 vector ,但没有解释构建器在那里。复杂得令人痛苦。
这是我的 Java 代码,我尝试将 Java POJO 序列化为等效的 Flatbuffers:
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());
}
每个 start() 方法都会抛出“FlatBuffers:对象序列化不得嵌套”异常,无法弄清楚如何执行此操作。
最佳答案
您使用单个FlatBufferBuilder
,但您必须在启动父级之前完成子级的序列化。
就您而言,这需要您将 FPath.startFPath
移至末尾,并将 FPath.startConnectionsVector
移至其之前。这意味着您需要将每个 FPathConnection
的偏移量存储在临时数组中。
这将使嵌套错误消失。
造成这种不便的原因是允许序列化过程在没有任何临时数据结构的情况下继续进行。
关于java - Flatbuffers:如何构建嵌套表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43150040/