flatbuffers icon indicating copy to clipboard operation
flatbuffers copied to clipboard

[C++] LookupByKey fails for table restored from json with unsorted elements

Open hanagasira opened this issue 2 years ago • 2 comments

  • The following test code fails [C++, VisualStudio 2022, Windows 10, master]
void JsonParseTest()
{
  flatbuffers::Parser parser;
  TEST_EQ(parser.Deserialize(MyGame::Example::MonsterBinarySchema::data(),
                                MyGame::Example::MonsterBinarySchema::size()),
          true);

  auto jsonStr = R"(
{
  "name": "lookupTest",
  "testarrayoftables": [
    { "name": "aaa" },
    { "name": "ccc" },
    { "name": "bbb" }
  ]
}
)";
  TEST_EQ(parser.ParseJson(jsonStr), true);
  auto monster = flatbuffers::GetRoot<MyGame::Example::Monster>(parser.builder_.GetBufferPointer());

  TEST_NOTNULL(monster->testarrayoftables()->LookupByKey("aaa"));
  // The test fails here.
  TEST_NOTNULL(monster->testarrayoftables()->LookupByKey("bbb"));
  TEST_NOTNULL(monster->testarrayoftables()->LookupByKey("ccc"));
}

When restoring a table from a json file, StructDef::has_key is not set, so the elements are not sorted and the test fails

hanagasira avatar Jul 17 '22 13:07 hanagasira

Is that JSON hand written or is it what is exported?

dbaileychess avatar Jul 26 '22 22:07 dbaileychess

This json was hand written.

The json exported from the table is already sorted and LookupByKey succeeds.

hanagasira avatar Jul 27 '22 14:07 hanagasira