1 /*
2 * Copyright 2014 Google Inc. All rights reserved.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "flatbuffers/idl.h"
18 #include "flatbuffers/util.h"
19
20 #include "monster_test_generated.h"
21 #include "monster_generated.h" // Already includes "flatbuffers/flatbuffers.h".
22
23 using namespace MyGame::Sample;
24
25 // This is an example of parsing text straight into a buffer and then
26 // generating flatbuffer (JSON) text from the buffer.
main(int,const char * [])27 int main(int /*argc*/, const char * /*argv*/[]) {
28 // load FlatBuffer schema (.fbs) and JSON from disk
29 std::string schema_file;
30 std::string json_file;
31 std::string bfbs_file;
32 bool ok =
33 flatbuffers::LoadFile("tests/monster_test.fbs", false, &schema_file) &&
34 flatbuffers::LoadFile("tests/monsterdata_test.golden", false, &json_file) &&
35 flatbuffers::LoadFile("tests/monster_test.bfbs", true, &bfbs_file);
36 if (!ok) {
37 printf("couldn't load files!\n");
38 return 1;
39 }
40
41 const char *include_directories[] = { "samples", "tests",
42 "tests/include_test", nullptr };
43 // parse fbs schema
44 flatbuffers::Parser parser1;
45 ok = parser1.Parse(schema_file.c_str(), include_directories);
46 assert(ok);
47
48 // inizialize parser by deserializing bfbs schema
49 flatbuffers::Parser parser2;
50 ok = parser2.Deserialize((uint8_t *)bfbs_file.c_str(), bfbs_file.length());
51 assert(ok);
52
53 // parse json in parser from fbs and bfbs
54 ok = parser1.Parse(json_file.c_str(), include_directories);
55 assert(ok);
56 ok = parser2.Parse(json_file.c_str(), include_directories);
57 assert(ok);
58
59 // to ensure it is correct, we now generate text back from the binary,
60 // and compare the two:
61 std::string jsongen1;
62 if (!GenerateText(parser1, parser1.builder_.GetBufferPointer(), &jsongen1)) {
63 printf("Couldn't serialize parsed data to JSON!\n");
64 return 1;
65 }
66
67 std::string jsongen2;
68 if (!GenerateText(parser2, parser2.builder_.GetBufferPointer(), &jsongen2)) {
69 printf("Couldn't serialize parsed data to JSON!\n");
70 return 1;
71 }
72
73 if (jsongen1 != jsongen2) {
74 printf("%s----------------\n%s", jsongen1.c_str(), jsongen2.c_str());
75 }
76
77 printf("The FlatBuffer has been parsed from JSON successfully.\n");
78 }
79