JsonNode.h 11 KB

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