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_generated.h"  // Already includes "flatbuffers/flatbuffers.h".
21 
22 using namespace MyGame::Sample;
23 
24 // This is an example of parsing text straight into a buffer and then
25 // generating flatbuffer (JSON) text from the buffer.
main(int,const char * [])26 int main(int /*argc*/, const char * /*argv*/ []) {
27   // load FlatBuffer schema (.fbs) and JSON from disk
28   std::string schemafile;
29   std::string jsonfile;
30   bool ok = flatbuffers::LoadFile("samples/monster.fbs", false, &schemafile) &&
31             flatbuffers::LoadFile("samples/monsterdata.json", false, &jsonfile);
32   if (!ok) {
33     printf("couldn't load files!\n");
34     return 1;
35   }
36 
37   // parse schema first, so we can use it to parse the data after
38   flatbuffers::Parser parser;
39   const char *include_directories[] = { "samples", nullptr };
40   ok = parser.Parse(schemafile.c_str(), include_directories) &&
41        parser.Parse(jsonfile.c_str(), include_directories);
42   assert(ok);
43 
44   // here, parser.builder_ contains a binary buffer that is the parsed data.
45 
46   // to ensure it is correct, we now generate text back from the binary,
47   // and compare the two:
48   std::string jsongen;
49   if (!GenerateText(parser, parser.builder_.GetBufferPointer(), &jsongen)) {
50     printf("Couldn't serialize parsed data to JSON!\n");
51     return 1;
52   }
53 
54   if (jsongen != jsonfile) {
55     printf("%s----------------\n%s", jsongen.c_str(), jsonfile.c_str());
56   }
57 
58   printf("The FlatBuffer has been parsed from JSON successfully.\n");
59 }
60