Make JSON supporting advanced union features (#7869)

This change allows user to decode binary with given schema to JSON
representation when schema defines union with struct.

Co-authored-by: Derek Bailey <derekbailey@google.com>
This commit is contained in:
Adam Oleksy 2023-04-26 07:37:06 +02:00 committed by GitHub
parent d6d83c3a92
commit ab716ee41d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 37 additions and 1 deletions

View File

@ -2584,7 +2584,8 @@ bool Parser::SupportsAdvancedUnionFeatures() const {
return (opts.lang_to_generate &
~(IDLOptions::kCpp | IDLOptions::kTs | IDLOptions::kPhp |
IDLOptions::kJava | IDLOptions::kCSharp | IDLOptions::kKotlin |
IDLOptions::kBinary | IDLOptions::kSwift | IDLOptions::kNim)) == 0;
IDLOptions::kBinary | IDLOptions::kSwift | IDLOptions::kNim |
IDLOptions::kJson)) == 0;
}
bool Parser::SupportsAdvancedArrayFeatures() const {

View File

@ -170,5 +170,38 @@ void JsonUnsortedArrayTest() {
TEST_NOTNULL(monster->testarrayoftables()->LookupByKey("ccc"));
}
void JsonUnionStructTest() {
// schema to parse data
auto schema = R"(
struct MyStruct { field: int; }
union UnionWithStruct { MyStruct }
table JsonUnionStructTest { union_with_struct: UnionWithStruct; }
root_type JsonUnionStructTest;
)";
// source text to parse and expected result of generation text back
auto json_source =R"({
union_with_struct_type: "MyStruct",
union_with_struct: {
field: 12345
}
}
)";
flatbuffers::Parser parser;
// set output language to JSON, so we assure that is supported
parser.opts.lang_to_generate = IDLOptions::kJson;
// parse schema first, so we assure that output language is supported
// and can use it to parse the data after
TEST_EQ(true, parser.Parse(schema));
TEST_EQ(true, parser.ParseJson(json_source));
// now generate text back from the binary, and compare the two:
std::string json_generated;
auto generate_result =
GenerateText(parser, parser.builder_.GetBufferPointer(), &json_generated);
TEST_EQ(true, generate_result);
TEST_EQ_STR(json_source, json_generated.c_str());
}
} // namespace tests
} // namespace flatbuffers

View File

@ -11,6 +11,7 @@ void JsonEnumsTest(const std::string& tests_data_path);
void JsonOptionalTest(const std::string& tests_data_path, bool default_scalars);
void ParseIncorrectMonsterJsonTest(const std::string& tests_data_path);
void JsonUnsortedArrayTest();
void JsonUnionStructTest();
} // namespace tests
} // namespace flatbuffers

View File

@ -1557,6 +1557,7 @@ int FlatBufferTests(const std::string &tests_data_path) {
ParseIncorrectMonsterJsonTest(tests_data_path);
FixedLengthArraySpanTest(tests_data_path);
DoNotRequireEofTest(tests_data_path);
JsonUnionStructTest();
#else
// Guard against -Wunused-parameter.
(void)tests_data_path;