2

我正在从此链接学习平面缓冲区,没有示例来演示如何存储字典(地图)。在此链接中提到了“在 java/Csharp 中存储字典” ,但我对此不太了解。我来自java背景。任何有关如何在 java 中的 flatbuffers 中存储字典/映射的示例都会有所帮助

4

1 回答 1

0

我意识到这是一个老问题,但是当我试图弄清楚同样的事情时,我遇到了它。这是我为获得“字典/地图”所做的工作

架构文件

namespace com.dictionary;

table DataItem{
  keyValue:string(key);
  name:string;
  age:int;
  codes[string];
}

table DictionaryRoot{
  items:[DataItem];
}

root_type DictionaryRoot;

当您通过 FlatBuffers 编译器运行flatc -j schema.fbs它时,它将生成两个 Java 文件,一个名为DictionaryRoot.java,另一个名为DataItem.java.

在您的 Java 应用程序中

使用这两个生成的 Java 文件,您将需要构建缓冲区。这必须从最里面的数据到最外面的数据来完成。DataItems所以你需要你的DictionaryRoot.

在此示例中,假设您有一个 Java 中的对象映射,您需要从中创建缓冲区。

List<Integer> offsets = new ArrayList<>();
FlatBufferBuilder builder = new FlatBufferBuilder(1024);

for (Entry<String, DataObj> entry : map.entrySet()) {
  DataObj dataObj = entry.getValue();

  // use the builder to create the data and keep track of their offsets
  int keyValueOffset = builder.createString(entry.getKey());
  int nameOffset = builder.createString(dataObj.getName());
  int ageOffset = dataObj.getAge();
  int[] codesOffsets = dataObj.getCodes().stream().mapToInt(builder::createString)
      .toArray();

  // use the builder to create a vector using the offsets from above
  int codesVectorOffset = DataItem.createCodesVector(builder, codesOffsets);

  // now with all the inner data offsets, create the DataItem
  DataItem.startDataItem(builder);

  DataItem.addKeyValue(builder, keyValueOffset);
  DataItem.addName(builder, nameOffset);
  DataItem.addAge(builder, ageOffset);
  DataItem.addCodes(builder, codesVectorOffset);

  // ensure you 'end' the DataItem to get the offset
  int dataItemOffset = DataItem.endDataItem(builder);

  // track the offsets
  offsets.add(dataItemOffset);
}

// use the builder to create a sorted vector from your offsets. This is critical
int sortedVectorOffset = builder.createSortedVectorOfTables(new DataItem(),
    offsets.stream().mapToInt(Integer::intValue).toArray());

// now with your sorted vector, create the DictionaryRoot
DictionaryRoot.startDictionaryRoot(builder);

DictionaryRoot.addItems(builder, sortedVectorOffset);

int dictRootOffset = DictionaryRoot.endDictionaryRoot(builder);

// signal to the builder you are done
builder.finish(dictRootOffset);

// Write data to file
FileOutputStream outputStream = new FileOutputStream("output.bin");
outputStream.write(builder.sizedByteArray());
outputStream.close();

我希望这将有助于其他人在他们使用 FlatBuffers 的过程中。

于 2021-01-09T20:40:17.543 回答