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