JsonNode.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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. /// Similar to convertTo but will assign data only if node is not null
  76. /// Othervice original data will be preserved
  77. /// Returns true if data was assigned
  78. template<typename Type>
  79. bool loadTo(Type & data) const;
  80. //operator [], for structs only - get child node by name
  81. JsonNode & operator[](std::string child);
  82. const JsonNode & operator[](std::string child) const;
  83. template <typename Handler> void serialize(Handler &h, const int version)
  84. {
  85. // simple saving - save json in its string interpretation
  86. if (h.saving)
  87. {
  88. std::ostringstream stream;
  89. stream << *this;
  90. std::string str = stream.str();
  91. h & str;
  92. }
  93. else
  94. {
  95. std::string str;
  96. h & str;
  97. JsonNode(str.c_str(), str.size()).swap(*this);
  98. }
  99. }
  100. };
  101. namespace JsonUtils
  102. {
  103. /**
  104. * @brief parse short bonus format, excluding type
  105. * @note sets duration to Permament
  106. */
  107. DLL_LINKAGE void parseTypedBonusShort(const JsonVector &source, Bonus *dest);
  108. ///
  109. DLL_LINKAGE Bonus * parseBonus (const JsonVector &ability_vec);
  110. DLL_LINKAGE Bonus * parseBonus (const JsonNode &bonus);
  111. DLL_LINKAGE void unparseBonus (JsonNode &node, const Bonus * bonus);
  112. DLL_LINKAGE void resolveIdentifier (si32 &var, const JsonNode &node, std::string name);
  113. DLL_LINKAGE void resolveIdentifier (const JsonNode &node, si32 &var);
  114. /**
  115. * @brief recursivly merges source into dest, replacing identical fields
  116. * struct : recursively calls this function
  117. * arrays : each entry will be merged recursively
  118. * values : value in source will replace value in dest
  119. * null : if value in source is present but set to null it will delete entry in dest
  120. * @note this function will destroy data in source
  121. */
  122. DLL_LINKAGE void merge(JsonNode & dest, JsonNode & source);
  123. /**
  124. * @brief recursivly merges source into dest, replacing identical fields
  125. * struct : recursively calls this function
  126. * arrays : each entry will be merged recursively
  127. * values : value in source will replace value in dest
  128. * null : if value in source is present but set to null it will delete entry in dest
  129. * @note this function will preserve data stored in source by creating copy
  130. */
  131. DLL_LINKAGE void mergeCopy(JsonNode & dest, JsonNode source);
  132. /**
  133. * @brief generate one Json structure from multiple files
  134. * @param files - list of filenames with parts of json structure
  135. */
  136. DLL_LINKAGE JsonNode assembleFromFiles(std::vector<std::string> files);
  137. /// removes all nodes that are identical to default entry in schema
  138. DLL_LINKAGE void minimize(JsonNode & node, const JsonNode& schema);
  139. /// check schema
  140. DLL_LINKAGE void validate(JsonNode & node, const JsonNode& schema);
  141. }
  142. //////////////////////////////////////////////////////////////////////////////////////////////////////
  143. // End of public section of the file. Anything below should be only used internally in JsonNode.cpp //
  144. //////////////////////////////////////////////////////////////////////////////////////////////////////
  145. namespace JsonDetail
  146. {
  147. // convertion helpers for JsonNode::convertTo (partial template function instantiation is illegal in c++)
  148. template <typename T, int arithm>
  149. struct JsonConvImpl;
  150. template <typename T>
  151. struct JsonConvImpl<T, 1>
  152. {
  153. static T convertImpl(const JsonNode & node)
  154. {
  155. return T((int)node.Float());
  156. }
  157. };
  158. template <typename T>
  159. struct JsonConvImpl<T, 0>
  160. {
  161. static T convertImpl(const JsonNode & node)
  162. {
  163. return node.Float();
  164. }
  165. };
  166. template<typename Type>
  167. struct JsonConverter
  168. {
  169. static Type convert(const JsonNode & node)
  170. {
  171. ///this should be triggered only for numeric types and enums
  172. static_assert(boost::mpl::or_<std::is_arithmetic<Type>, std::is_enum<Type>, boost::is_class<Type> >::value, "Unsupported type for JsonNode::convertTo()!");
  173. return JsonConvImpl<Type, boost::mpl::or_<std::is_enum<Type>, boost::is_class<Type> >::value >::convertImpl(node);
  174. }
  175. };
  176. template<typename Type>
  177. struct JsonConverter<std::map<std::string, Type> >
  178. {
  179. static std::map<std::string, Type> convert(const JsonNode & node)
  180. {
  181. std::map<std::string, Type> ret;
  182. BOOST_FOREACH(auto entry, node.Struct())
  183. {
  184. ret.insert(entry.first, entry.second.convertTo<Type>());
  185. }
  186. return ret;
  187. }
  188. };
  189. template<typename Type>
  190. struct JsonConverter<std::set<Type> >
  191. {
  192. static std::set<Type> convert(const JsonNode & node)
  193. {
  194. std::set<Type> ret;
  195. BOOST_FOREACH(auto entry, node.Vector())
  196. {
  197. ret.insert(entry.convertTo<Type>());
  198. }
  199. return ret;
  200. }
  201. };
  202. template<typename Type>
  203. struct JsonConverter<std::vector<Type> >
  204. {
  205. static std::vector<Type> convert(const JsonNode & node)
  206. {
  207. std::vector<Type> ret;
  208. BOOST_FOREACH(auto entry, node.Vector())
  209. {
  210. ret.push_back(entry.convertTo<Type>());
  211. }
  212. return ret;
  213. }
  214. };
  215. template<>
  216. struct JsonConverter<std::string>
  217. {
  218. static std::string convert(const JsonNode & node)
  219. {
  220. return node.String();
  221. }
  222. };
  223. template<>
  224. struct JsonConverter<bool>
  225. {
  226. static bool convert(const JsonNode & node)
  227. {
  228. return node.Bool();
  229. }
  230. };
  231. class JsonWriter
  232. {
  233. //prefix for each line (tabulation)
  234. std::string prefix;
  235. std::ostream &out;
  236. public:
  237. template<typename Iterator>
  238. void writeContainer(Iterator begin, Iterator end);
  239. void writeEntry(JsonMap::const_iterator entry);
  240. void writeEntry(JsonVector::const_iterator entry);
  241. void writeString(const std::string &string);
  242. void writeNode(const JsonNode &node);
  243. JsonWriter(std::ostream &output, const JsonNode &node);
  244. };
  245. //Tiny string class that uses const char* as data for speed, members are private
  246. //for ease of debugging and some compatibility with std::string
  247. class constString
  248. {
  249. const char *data;
  250. const size_t datasize;
  251. public:
  252. constString(const char * inputString, size_t stringSize):
  253. data(inputString),
  254. datasize(stringSize)
  255. {
  256. }
  257. inline size_t size() const
  258. {
  259. return datasize;
  260. };
  261. inline const char& operator[] (size_t position)
  262. {
  263. assert (position < datasize);
  264. return data[position];
  265. }
  266. };
  267. //Internal class for string -> JsonNode conversion
  268. class JsonParser
  269. {
  270. std::string errors; // Contains description of all encountered errors
  271. constString input; // Input data
  272. ui32 lineCount; // Currently parsed line, starting from 1
  273. size_t lineStart; // Position of current line start
  274. size_t pos; // Current position of parser
  275. //Helpers
  276. bool extractEscaping(std::string &str);
  277. bool extractLiteral(const std::string &literal);
  278. bool extractString(std::string &string);
  279. bool extractWhitespace(bool verbose = true);
  280. bool extractSeparator();
  281. bool extractElement(JsonNode &node, char terminator);
  282. //Methods for extracting JSON data
  283. bool extractArray(JsonNode &node);
  284. bool extractFalse(JsonNode &node);
  285. bool extractFloat(JsonNode &node);
  286. bool extractNull(JsonNode &node);
  287. bool extractString(JsonNode &node);
  288. bool extractStruct(JsonNode &node);
  289. bool extractTrue(JsonNode &node);
  290. bool extractValue(JsonNode &node);
  291. //Add error\warning message to list
  292. bool error(const std::string &message, bool warning=false);
  293. public:
  294. JsonParser(const char * inputString, size_t stringSize, JsonNode &root);
  295. };
  296. //Internal class for Json validation, used automaticaly in JsonNode constructor. Behaviour:
  297. // - "schema" entry from root node is used for validation and will be removed
  298. // - any missing entries will be replaced with default value from schema (if present)
  299. // - if entry uses different type than defined in schema it will be removed
  300. // - entries nod described in schema will be kept unchanged
  301. class JsonValidator
  302. {
  303. std::string errors; // Contains description of all encountered errors
  304. std::list<std::string> currentPath; // path from root node to current one
  305. bool minimize;
  306. bool validateType(JsonNode &node, const JsonNode &schema, JsonNode::JsonType type);
  307. bool validateSchema(JsonNode::JsonType &type, const JsonNode &schema);
  308. bool validateNode(JsonNode &node, const JsonNode &schema, const std::string &name);
  309. bool validateItems(JsonNode &node, const JsonNode &schema);
  310. bool validateProperties(JsonNode &node, const JsonNode &schema);
  311. bool addMessage(const std::string &message);
  312. public:
  313. // validate node with "schema" entry
  314. JsonValidator(JsonNode &root, bool minimize=false);
  315. // validate with external schema
  316. JsonValidator(JsonNode &root, const JsonNode &schema, bool minimize=false);
  317. };
  318. } // namespace JsonDetail
  319. template<typename Type>
  320. Type JsonNode::convertTo() const
  321. {
  322. return JsonDetail::JsonConverter<Type>::convert(*this);
  323. }
  324. template<typename Type>
  325. bool JsonNode::loadTo(Type & data) const
  326. {
  327. if (!isNull())
  328. data = convertTo<Type>();
  329. return !isNull();
  330. }