JsonNode.h 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. /*
  2. * JsonNode.h, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #pragma once
  11. class JsonNode;
  12. typedef std::map <std::string, JsonNode> JsonMap;
  13. typedef std::vector <JsonNode> JsonVector;
  14. DLL_LINKAGE std::ostream & operator<<(std::ostream &out, const JsonNode &node);
  15. struct Bonus;
  16. class ResourceID;
  17. class DLL_LINKAGE JsonNode
  18. {
  19. public:
  20. enum JsonType
  21. {
  22. DATA_NULL,
  23. DATA_BOOL,
  24. DATA_FLOAT,
  25. DATA_STRING,
  26. DATA_VECTOR,
  27. DATA_STRUCT
  28. };
  29. private:
  30. union JsonData
  31. {
  32. bool Bool;
  33. double Float;
  34. std::string* String;
  35. JsonVector* Vector;
  36. JsonMap* Struct;
  37. };
  38. JsonType type;
  39. JsonData data;
  40. public:
  41. //Create empty node
  42. JsonNode(JsonType Type = DATA_NULL);
  43. //Create tree from Json-formatted input
  44. explicit JsonNode(const char * data, size_t datasize);
  45. //Create tree from JSON file
  46. explicit JsonNode(ResourceID && fileURI);
  47. //Copy c-tor
  48. JsonNode(const JsonNode &copy);
  49. ~JsonNode();
  50. void swap(JsonNode &b);
  51. JsonNode& operator =(JsonNode node);
  52. bool operator == (const JsonNode &other) const;
  53. bool operator != (const JsonNode &other) const;
  54. //Convert node to another type. Converting to NULL will clear all data
  55. void setType(JsonType Type);
  56. JsonType getType() const;
  57. bool isNull() const;
  58. //non-const accessors, node will change type on type mismatch
  59. bool & Bool();
  60. double & Float();
  61. std::string & String();
  62. JsonVector & Vector();
  63. JsonMap & Struct();
  64. //const accessors, will cause assertion failure on type mismatch
  65. const bool & Bool() const;
  66. const double & Float() const;
  67. const std::string & String() const;
  68. const JsonVector & Vector() const;
  69. const JsonMap & Struct() const;
  70. /// convert json tree into specified type. Json tree must have same type as Type
  71. /// Valid types: bool, string, any numeric, map and vector
  72. /// example: convertTo< std::map< std::vector<int> > >();
  73. template<typename Type>
  74. Type convertTo() const;
  75. //operator [], for structs only - get child node by name
  76. JsonNode & operator[](std::string child);
  77. const JsonNode & operator[](std::string child) const;
  78. template <typename Handler> void serialize(Handler &h, const int version)
  79. {
  80. // simple saving - save json in its string interpretation
  81. if (h.saving)
  82. {
  83. std::ostringstream stream;
  84. stream << *this;
  85. std::string str = stream.str();
  86. h & str;
  87. }
  88. else
  89. {
  90. std::string str;
  91. h & str;
  92. JsonNode(str.c_str(), str.size()).swap(*this);
  93. }
  94. }
  95. };
  96. namespace JsonUtils
  97. {
  98. DLL_LINKAGE Bonus * parseBonus (const JsonVector &ability_vec);
  99. DLL_LINKAGE Bonus * parseBonus (const JsonNode &bonus);
  100. DLL_LINKAGE void unparseBonus (JsonNode &node, const Bonus * bonus);
  101. DLL_LINKAGE void resolveIdentifier (si32 &var, const JsonNode &node, std::string name);
  102. DLL_LINKAGE void resolveIdentifier (const JsonNode &node, si32 &var);
  103. /// recursivly merges source into dest, replacing identical fields
  104. /// struct : recursively calls this function
  105. /// arrays : each entry will be merged recursively
  106. /// values : value in source will replace value in dest
  107. /// null : if value in source is present but set to null it will delete entry in dest
  108. /// this function will destroy data in source
  109. DLL_LINKAGE void merge(JsonNode & dest, JsonNode & source);
  110. /// this function will preserve data stored in source by creating copy
  111. DLL_LINKAGE void mergeCopy(JsonNode & dest, JsonNode source);
  112. /**
  113. * @brief generate one Json structure from multiple files
  114. * @param files - list of filenames with parts of json structure
  115. */
  116. DLL_LINKAGE JsonNode assembleFromFiles(std::vector<std::string> files);
  117. /// removes all nodes that are identical to default entry in schema
  118. DLL_LINKAGE void minimize(JsonNode & node, const JsonNode& schema);
  119. /// check schema
  120. DLL_LINKAGE void validate(JsonNode & node, const JsonNode& schema);
  121. }
  122. //////////////////////////////////////////////////////////////////////////////////////////////////////
  123. // End of public section of the file. Anything below should be only used internally in JsonNode.cpp //
  124. //////////////////////////////////////////////////////////////////////////////////////////////////////
  125. namespace JsonDetail
  126. {
  127. // convertion helpers for JsonNode::convertTo (partial template function instantiation is illegal in c++)
  128. template<typename Type>
  129. struct JsonConverter
  130. {
  131. static Type convert(const JsonNode & node)
  132. {
  133. ///this should be triggered only for numeric types
  134. static_assert(std::is_arithmetic<Type>::value, "Unsupported type for JsonNode::convertTo()!");
  135. return node.Float();
  136. }
  137. };
  138. template<typename Type>
  139. struct JsonConverter<std::map<std::string, Type> >
  140. {
  141. static std::map<std::string, Type> convert(const JsonNode & node)
  142. {
  143. std::map<std::string, Type> ret;
  144. BOOST_FOREACH(auto entry, node.Struct())
  145. {
  146. ret.insert(entry.first, entry.second.convertTo<Type>());
  147. }
  148. return ret;
  149. }
  150. };
  151. template<typename Type>
  152. struct JsonConverter<std::set<Type> >
  153. {
  154. static std::set<Type> convert(const JsonNode & node)
  155. {
  156. std::set<Type> ret;
  157. BOOST_FOREACH(auto entry, node.Vector())
  158. {
  159. ret.insert(entry.convertTo<Type>());
  160. }
  161. return ret;
  162. }
  163. };
  164. template<typename Type>
  165. struct JsonConverter<std::vector<Type> >
  166. {
  167. static std::vector<Type> convert(const JsonNode & node)
  168. {
  169. std::vector<Type> ret;
  170. BOOST_FOREACH(auto entry, node.Vector())
  171. {
  172. ret.push_back(entry.convertTo<Type>());
  173. }
  174. return ret;
  175. }
  176. };
  177. template<>
  178. struct JsonConverter<std::string>
  179. {
  180. static std::string convert(const JsonNode & node)
  181. {
  182. return node.String();
  183. }
  184. };
  185. template<>
  186. struct JsonConverter<bool>
  187. {
  188. static bool convert(const JsonNode & node)
  189. {
  190. return node.Bool();
  191. }
  192. };
  193. class JsonWriter
  194. {
  195. //prefix for each line (tabulation)
  196. std::string prefix;
  197. std::ostream &out;
  198. public:
  199. template<typename Iterator>
  200. void writeContainer(Iterator begin, Iterator end);
  201. void writeEntry(JsonMap::const_iterator entry);
  202. void writeEntry(JsonVector::const_iterator entry);
  203. void writeString(const std::string &string);
  204. void writeNode(const JsonNode &node);
  205. JsonWriter(std::ostream &output, const JsonNode &node);
  206. };
  207. //Tiny string class that uses const char* as data for speed, members are private
  208. //for ease of debugging and some compatibility with std::string
  209. class constString
  210. {
  211. const char *data;
  212. const size_t datasize;
  213. public:
  214. constString(const char * inputString, size_t stringSize):
  215. data(inputString),
  216. datasize(stringSize)
  217. {
  218. }
  219. inline size_t size() const
  220. {
  221. return datasize;
  222. };
  223. inline const char& operator[] (size_t position)
  224. {
  225. assert (position < datasize);
  226. return data[position];
  227. }
  228. };
  229. //Internal class for string -> JsonNode conversion
  230. class JsonParser
  231. {
  232. std::string errors; // Contains description of all encountered errors
  233. constString input; // Input data
  234. ui32 lineCount; // Currently parsed line, starting from 1
  235. size_t lineStart; // Position of current line start
  236. size_t pos; // Current position of parser
  237. //Helpers
  238. bool extractEscaping(std::string &str);
  239. bool extractLiteral(const std::string &literal);
  240. bool extractString(std::string &string);
  241. bool extractWhitespace(bool verbose = true);
  242. bool extractSeparator();
  243. bool extractElement(JsonNode &node, char terminator);
  244. //Methods for extracting JSON data
  245. bool extractArray(JsonNode &node);
  246. bool extractFalse(JsonNode &node);
  247. bool extractFloat(JsonNode &node);
  248. bool extractNull(JsonNode &node);
  249. bool extractString(JsonNode &node);
  250. bool extractStruct(JsonNode &node);
  251. bool extractTrue(JsonNode &node);
  252. bool extractValue(JsonNode &node);
  253. //Add error\warning message to list
  254. bool error(const std::string &message, bool warning=false);
  255. public:
  256. JsonParser(const char * inputString, size_t stringSize, JsonNode &root);
  257. };
  258. //Internal class for Json validation, used automaticaly in JsonNode constructor. Behaviour:
  259. // - "schema" entry from root node is used for validation and will be removed
  260. // - any missing entries will be replaced with default value from schema (if present)
  261. // - if entry uses different type than defined in schema it will be removed
  262. // - entries nod described in schema will be kept unchanged
  263. class JsonValidator
  264. {
  265. std::string errors; // Contains description of all encountered errors
  266. std::list<std::string> currentPath; // path from root node to current one
  267. bool minimize;
  268. bool validateType(JsonNode &node, const JsonNode &schema, JsonNode::JsonType type);
  269. bool validateSchema(JsonNode::JsonType &type, const JsonNode &schema);
  270. bool validateNode(JsonNode &node, const JsonNode &schema, const std::string &name);
  271. bool validateItems(JsonNode &node, const JsonNode &schema);
  272. bool validateProperties(JsonNode &node, const JsonNode &schema);
  273. bool addMessage(const std::string &message);
  274. public:
  275. // validate node with "schema" entry
  276. JsonValidator(JsonNode &root, bool minimize=false);
  277. // validate with external schema
  278. JsonValidator(JsonNode &root, const JsonNode &schema, bool minimize=false);
  279. };
  280. } // namespace JsonDetail
  281. template<typename Type>
  282. Type JsonNode::convertTo() const
  283. {
  284. return JsonDetail::JsonConverter<Type>::convert(*this);
  285. }