Reputation: 11
I'm trying to set a new custom root before parsing a JSon into a structure via flatbuffers.
The Corresponding FSB has a root_type already and I want to override it only to be able to parse it into a struct once.
The SetRootType("NonRootStructInFbsT") fails
The documentation of the API says, this can be used to override the current root which is exactly what I want to do.
std::string schemaText;
std::string schemaFile("MySchema.fbs");
if(not flatbuffers::FileExists(schemaFile.c_str())) {
error("Schema file inaccessible: ", schemaFile);
return nullptr;
}
if(not flatbuffers::LoadFile(schemaFile.c_str(), false, &schemaText)) {
error(TAG, "Failed to load schema file: ", schemaFile);
return nullptr;
}
info("Read schema file: ", schemaText.size(), schemaText);
flatbuffers::Parser parser;
if(not parser.SetRootType("NonRootStructInFbsT")) {
error("Unable to set root type: ", customRoot);
return nullptr;
}
info("Set the root type: ", customRoot);
I always get the error message Unable to set root type: NonRootStructInFbsT
Upvotes: 0
Views: 449
Reputation: 10979
The posted code lacks call of flatbuffers::Parser::Parse
with schema contents. Your code:
std::string schemaText;
std::string schemaFile("MySchema.fbs");
if(not flatbuffers::FileExists(schemaFile.c_str())) {
error("Schema file inaccessible: ", schemaFile);
return nullptr;
}
if(not flatbuffers::LoadFile(schemaFile.c_str(), false, &schemaText)) {
error(TAG, "Failed to load schema file: ", schemaFile);
return nullptr;
}
info("Read schema file: ", schemaText.size(), schemaText);
flatbuffers::Parser parser;
It is all OK, but here we have contents of schema file in schemaText
and empty parser
with default options. Too early to set root types. We should read the schema to parser
with something like:
if(not parser.Parse(schemaText)) {
error(TAG, "Defective schema: ", parser.error_);
return nullptr;
}
After that if we reached here we have parser
with schema and so in that schema we can chose also root type:
if(not parser.SetRootType("NonRootStructInFbsT")) {
error("Unable to set root type: ", customRoot);
return nullptr;
}
info("Set the root type: ", customRoot);
Note that parser.error_
is quite informative about any errors you face during parser
usage.
Upvotes: 1
Reputation: 6074
The root of a FlatBuffer can only be a table
, so root_type
and SetRootType
will reject names of anything else, like a struct
or a union
.
Furthermore, the fact that the name ends in T
appears to refer to an "object API" type. These are names purely in the generated code, you need to supply names as they are in the schema.
Upvotes: 1