JsonNode.h 8.7 KB

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