JsonNode.h 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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. struct Bonus;
  15. class ResourceID;
  16. class DLL_LINKAGE JsonNode
  17. {
  18. public:
  19. enum class JsonType
  20. {
  21. DATA_NULL,
  22. DATA_BOOL,
  23. DATA_FLOAT,
  24. DATA_STRING,
  25. DATA_VECTOR,
  26. DATA_STRUCT,
  27. DATA_INTEGER
  28. };
  29. private:
  30. union JsonData
  31. {
  32. bool Bool;
  33. double Float;
  34. std::string* String;
  35. JsonVector* Vector;
  36. JsonMap* Struct;
  37. si64 Integer;
  38. };
  39. JsonType type;
  40. JsonData data;
  41. public:
  42. /// free to use metadata field
  43. std::string meta;
  44. //Create empty node
  45. JsonNode(JsonType Type = JsonType::DATA_NULL);
  46. //Create tree from Json-formatted input
  47. explicit JsonNode(const char * data, size_t datasize);
  48. //Create tree from JSON file
  49. explicit JsonNode(ResourceID && fileURI);
  50. explicit JsonNode(const ResourceID & fileURI);
  51. explicit JsonNode(ResourceID && fileURI, bool & isValidSyntax);
  52. //Copy c-tor
  53. JsonNode(const JsonNode &copy);
  54. ~JsonNode();
  55. void swap(JsonNode &b);
  56. JsonNode& operator =(JsonNode node);
  57. bool operator == (const JsonNode &other) const;
  58. bool operator != (const JsonNode &other) const;
  59. void setMeta(std::string metadata, bool recursive = true);
  60. /// Convert node to another type. Converting to nullptr will clear all data
  61. void setType(JsonType Type);
  62. JsonType getType() const;
  63. bool isNull() const;
  64. bool isNumber() const;
  65. /// removes all data from node and sets type to null
  66. void clear();
  67. /// non-const accessors, node will change type on type mismatch
  68. bool & Bool();
  69. double & Float();
  70. si64 & Integer();
  71. std::string & String();
  72. JsonVector & Vector();
  73. JsonMap & Struct();
  74. /// const accessors, will cause assertion failure on type mismatch
  75. bool Bool() const;
  76. ///float and integer allowed
  77. double Float() const;
  78. ///only integer allowed
  79. si64 Integer() const;
  80. const std::string & String() const;
  81. const JsonVector & Vector() const;
  82. const JsonMap & Struct() const;
  83. /// returns resolved "json pointer" (string in format "/path/to/node")
  84. const JsonNode & resolvePointer(const std::string & jsonPointer) const;
  85. JsonNode & resolvePointer(const std::string & jsonPointer);
  86. /// convert json tree into specified type. Json tree must have same type as Type
  87. /// Valid types: bool, string, any numeric, map and vector
  88. /// example: convertTo< std::map< std::vector<int> > >();
  89. template<typename Type>
  90. Type convertTo() const;
  91. //operator [], for structs only - get child node by name
  92. JsonNode & operator[](std::string child);
  93. const JsonNode & operator[](std::string child) const;
  94. std::string toJson() const;
  95. template <typename Handler> void serialize(Handler &h, const int version)
  96. {
  97. h & meta;
  98. h & type;
  99. switch (type) {
  100. break; case JsonType::DATA_NULL:
  101. break; case JsonType::DATA_BOOL: h & data.Bool;
  102. break; case JsonType::DATA_FLOAT: h & data.Float;
  103. break; case JsonType::DATA_STRING: h & data.String;
  104. break; case JsonType::DATA_VECTOR: h & data.Vector;
  105. break; case JsonType::DATA_STRUCT: h & data.Struct;
  106. }
  107. if(version >= 770)
  108. {
  109. if(type == JsonType::DATA_INTEGER)
  110. h & data.Integer;
  111. }
  112. }
  113. };
  114. namespace JsonUtils
  115. {
  116. /**
  117. * @brief parse short bonus format, excluding type
  118. * @note sets duration to Permament
  119. */
  120. DLL_LINKAGE void parseTypedBonusShort(const JsonVector &source, std::shared_ptr<Bonus> dest);
  121. ///
  122. DLL_LINKAGE std::shared_ptr<Bonus> parseBonus(const JsonVector &ability_vec);
  123. DLL_LINKAGE std::shared_ptr<Bonus> parseBonus(const JsonNode &ability);
  124. DLL_LINKAGE bool parseBonus(const JsonNode &ability, Bonus *placement);
  125. DLL_LINKAGE void unparseBonus (JsonNode &node, const std::shared_ptr<Bonus>& bonus);
  126. DLL_LINKAGE void resolveIdentifier(si32 &var, const JsonNode &node, std::string name);
  127. DLL_LINKAGE void resolveIdentifier(const JsonNode &node, si32 &var);
  128. /**
  129. * @brief recursively merges source into dest, replacing identical fields
  130. * struct : recursively calls this function
  131. * arrays : each entry will be merged recursively
  132. * values : value in source will replace value in dest
  133. * null : if value in source is present but set to null it will delete entry in dest
  134. * @note this function will destroy data in source
  135. */
  136. DLL_LINKAGE void merge(JsonNode & dest, JsonNode & source);
  137. /**
  138. * @brief recursively merges source into dest, replacing identical fields
  139. * struct : recursively calls this function
  140. * arrays : each entry will be merged recursively
  141. * values : value in source will replace value in dest
  142. * null : if value in source is present but set to null it will delete entry in dest
  143. * @note this function will preserve data stored in source by creating copy
  144. */
  145. DLL_LINKAGE void mergeCopy(JsonNode & dest, JsonNode source);
  146. /** @brief recursively merges descendant into copy of base node
  147. * Result emulates inheritance semantic
  148. *
  149. *
  150. */
  151. DLL_LINKAGE void inherit(JsonNode & descendant, const JsonNode & base);
  152. /**
  153. * @brief generate one Json structure from multiple files
  154. * @param files - list of filenames with parts of json structure
  155. */
  156. DLL_LINKAGE JsonNode assembleFromFiles(std::vector<std::string> files);
  157. DLL_LINKAGE JsonNode assembleFromFiles(std::vector<std::string> files, bool & isValid);
  158. /// This version loads all files with same name (overridden by mods)
  159. DLL_LINKAGE JsonNode assembleFromFiles(std::string filename);
  160. /**
  161. * @brief removes all nodes that are identical to default entry in schema
  162. * @param node - JsonNode to minimize
  163. * @param schemaName - name of schema to use
  164. * @note for minimizing data must be valid against given schema
  165. */
  166. DLL_LINKAGE void minimize(JsonNode & node, std::string schemaName);
  167. /// opposed to minimize, adds all missing, required entries that have default value
  168. DLL_LINKAGE void maximize(JsonNode & node, std::string schemaName);
  169. /**
  170. * @brief validate node against specified schema
  171. * @param node - JsonNode to check
  172. * @param schemaName - name of schema to use
  173. * @param dataName - some way to identify data (printed in console in case of errors)
  174. * @returns true if data in node fully compilant with schema
  175. */
  176. DLL_LINKAGE bool validate(const JsonNode & node, std::string schemaName, std::string dataName);
  177. /// get schema by json URI: vcmi:<name of file in schemas directory>#<entry in file, optional>
  178. /// example: schema "vcmi:settings" is used to check user settings
  179. DLL_LINKAGE const JsonNode & getSchema(std::string URI);
  180. }
  181. namespace JsonDetail
  182. {
  183. // conversion helpers for JsonNode::convertTo (partial template function instantiation is illegal in c++)
  184. template <typename T, int arithm>
  185. struct JsonConvImpl;
  186. template <typename T>
  187. struct JsonConvImpl<T, 1>
  188. {
  189. static T convertImpl(const JsonNode & node)
  190. {
  191. return T((int)node.Float());
  192. }
  193. };
  194. template <typename T>
  195. struct JsonConvImpl<T, 0>
  196. {
  197. static T convertImpl(const JsonNode & node)
  198. {
  199. return node.Float();
  200. }
  201. };
  202. template<typename Type>
  203. struct JsonConverter
  204. {
  205. static Type convert(const JsonNode & node)
  206. {
  207. ///this should be triggered only for numeric types and enums
  208. static_assert(boost::mpl::or_<std::is_arithmetic<Type>, std::is_enum<Type>, boost::is_class<Type> >::value, "Unsupported type for JsonNode::convertTo()!");
  209. return JsonConvImpl<Type, boost::mpl::or_<std::is_enum<Type>, boost::is_class<Type> >::value >::convertImpl(node);
  210. }
  211. };
  212. template<typename Type>
  213. struct JsonConverter<std::map<std::string, Type> >
  214. {
  215. static std::map<std::string, Type> convert(const JsonNode & node)
  216. {
  217. std::map<std::string, Type> ret;
  218. for (const JsonMap::value_type & entry : node.Struct())
  219. {
  220. ret.insert(entry.first, entry.second.convertTo<Type>());
  221. }
  222. return ret;
  223. }
  224. };
  225. template<typename Type>
  226. struct JsonConverter<std::set<Type> >
  227. {
  228. static std::set<Type> convert(const JsonNode & node)
  229. {
  230. std::set<Type> ret;
  231. for(const JsonVector::value_type & entry : node.Vector())
  232. {
  233. ret.insert(entry.convertTo<Type>());
  234. }
  235. return ret;
  236. }
  237. };
  238. template<typename Type>
  239. struct JsonConverter<std::vector<Type> >
  240. {
  241. static std::vector<Type> convert(const JsonNode & node)
  242. {
  243. std::vector<Type> ret;
  244. for (const JsonVector::value_type & entry: node.Vector())
  245. {
  246. ret.push_back(entry.convertTo<Type>());
  247. }
  248. return ret;
  249. }
  250. };
  251. template<>
  252. struct JsonConverter<std::string>
  253. {
  254. static std::string convert(const JsonNode & node)
  255. {
  256. return node.String();
  257. }
  258. };
  259. template<>
  260. struct JsonConverter<bool>
  261. {
  262. static bool convert(const JsonNode & node)
  263. {
  264. return node.Bool();
  265. }
  266. };
  267. }
  268. template<typename Type>
  269. Type JsonNode::convertTo() const
  270. {
  271. return JsonDetail::JsonConverter<Type>::convert(*this);
  272. }