JsonNode.h 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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. bool isEmpty() const;
  66. /// removes all data from node and sets type to null
  67. void clear();
  68. /// non-const accessors, node will change type on type mismatch
  69. bool & Bool();
  70. double & Float();
  71. si64 & Integer();
  72. std::string & String();
  73. JsonVector & Vector();
  74. JsonMap & Struct();
  75. /// const accessors, will cause assertion failure on type mismatch
  76. bool Bool() const;
  77. ///float and integer allowed
  78. double Float() const;
  79. ///only integer allowed
  80. si64 Integer() const;
  81. const std::string & String() const;
  82. const JsonVector & Vector() const;
  83. const JsonMap & Struct() const;
  84. /// returns resolved "json pointer" (string in format "/path/to/node")
  85. const JsonNode & resolvePointer(const std::string & jsonPointer) const;
  86. JsonNode & resolvePointer(const std::string & jsonPointer);
  87. /// convert json tree into specified type. Json tree must have same type as Type
  88. /// Valid types: bool, string, any numeric, map and vector
  89. /// example: convertTo< std::map< std::vector<int> > >();
  90. template<typename Type>
  91. Type convertTo() const;
  92. //operator [], for structs only - get child node by name
  93. JsonNode & operator[](std::string child);
  94. const JsonNode & operator[](std::string child) const;
  95. std::string toJson() const;
  96. template <typename Handler> void serialize(Handler &h, const int version)
  97. {
  98. h & meta;
  99. h & type;
  100. switch(type)
  101. {
  102. case JsonType::DATA_NULL:
  103. break;
  104. case JsonType::DATA_BOOL:
  105. h & data.Bool;
  106. break;
  107. case JsonType::DATA_FLOAT:
  108. h & data.Float;
  109. break;
  110. case JsonType::DATA_STRING:
  111. h & data.String;
  112. break;
  113. case JsonType::DATA_VECTOR:
  114. h & data.Vector;
  115. break;
  116. case JsonType::DATA_STRUCT:
  117. h & data.Struct;
  118. break;
  119. case JsonType::DATA_INTEGER:
  120. if(version >= 770)
  121. {
  122. h & data.Integer;
  123. }
  124. break;
  125. }
  126. }
  127. };
  128. namespace JsonUtils
  129. {
  130. /**
  131. * @brief parse short bonus format, excluding type
  132. * @note sets duration to Permament
  133. */
  134. DLL_LINKAGE void parseTypedBonusShort(const JsonVector &source, std::shared_ptr<Bonus> dest);
  135. ///
  136. DLL_LINKAGE std::shared_ptr<Bonus> parseBonus(const JsonVector &ability_vec);
  137. DLL_LINKAGE std::shared_ptr<Bonus> parseBonus(const JsonNode &ability);
  138. DLL_LINKAGE bool parseBonus(const JsonNode &ability, Bonus *placement);
  139. DLL_LINKAGE void unparseBonus (JsonNode &node, const std::shared_ptr<Bonus>& bonus);
  140. DLL_LINKAGE void resolveIdentifier(si32 &var, const JsonNode &node, std::string name);
  141. DLL_LINKAGE void resolveIdentifier(const JsonNode &node, si32 &var);
  142. /**
  143. * @brief recursively merges source into dest, replacing identical fields
  144. * struct : recursively calls this function
  145. * arrays : each entry will be merged recursively
  146. * values : value in source will replace value in dest
  147. * null : if value in source is present but set to null it will delete entry in dest
  148. * @note this function will destroy data in source
  149. */
  150. DLL_LINKAGE void merge(JsonNode & dest, JsonNode & source);
  151. /**
  152. * @brief recursively merges source into dest, replacing identical fields
  153. * struct : recursively calls this function
  154. * arrays : each entry will be merged recursively
  155. * values : value in source will replace value in dest
  156. * null : if value in source is present but set to null it will delete entry in dest
  157. * @note this function will preserve data stored in source by creating copy
  158. */
  159. DLL_LINKAGE void mergeCopy(JsonNode & dest, JsonNode source);
  160. /** @brief recursively merges descendant into copy of base node
  161. * Result emulates inheritance semantic
  162. *
  163. *
  164. */
  165. DLL_LINKAGE void inherit(JsonNode & descendant, const JsonNode & base);
  166. /**
  167. * @brief construct node representing the common structure of input nodes
  168. * @param pruneEmpty - omit common properties whose intersection is empty
  169. * different types: null
  170. * struct: recursive intersect on common properties
  171. * other: input if equal, null otherwise
  172. */
  173. DLL_LINKAGE JsonNode intersect(const JsonNode & a, const JsonNode & b, bool pruneEmpty = true);
  174. DLL_LINKAGE JsonNode intersect(const std::vector<JsonNode> & nodes, bool pruneEmpty = true);
  175. /**
  176. * @brief construct node representing the difference "node - base"
  177. * merging difference with base gives node
  178. */
  179. DLL_LINKAGE JsonNode difference(const JsonNode & node, const JsonNode & base);
  180. /**
  181. * @brief generate one Json structure from multiple files
  182. * @param files - list of filenames with parts of json structure
  183. */
  184. DLL_LINKAGE JsonNode assembleFromFiles(std::vector<std::string> files);
  185. DLL_LINKAGE JsonNode assembleFromFiles(std::vector<std::string> files, bool & isValid);
  186. /// This version loads all files with same name (overridden by mods)
  187. DLL_LINKAGE JsonNode assembleFromFiles(std::string filename);
  188. /**
  189. * @brief removes all nodes that are identical to default entry in schema
  190. * @param node - JsonNode to minimize
  191. * @param schemaName - name of schema to use
  192. * @note for minimizing data must be valid against given schema
  193. */
  194. DLL_LINKAGE void minimize(JsonNode & node, std::string schemaName);
  195. /// opposed to minimize, adds all missing, required entries that have default value
  196. DLL_LINKAGE void maximize(JsonNode & node, std::string schemaName);
  197. /**
  198. * @brief validate node against specified schema
  199. * @param node - JsonNode to check
  200. * @param schemaName - name of schema to use
  201. * @param dataName - some way to identify data (printed in console in case of errors)
  202. * @returns true if data in node fully compilant with schema
  203. */
  204. DLL_LINKAGE bool validate(const JsonNode & node, std::string schemaName, std::string dataName);
  205. /// get schema by json URI: vcmi:<name of file in schemas directory>#<entry in file, optional>
  206. /// example: schema "vcmi:settings" is used to check user settings
  207. DLL_LINKAGE const JsonNode & getSchema(std::string URI);
  208. /// for easy construction of JsonNodes; helps with inserting primitives into vector node
  209. DLL_LINKAGE JsonNode boolNode(bool value);
  210. DLL_LINKAGE JsonNode floatNode(double value);
  211. DLL_LINKAGE JsonNode stringNode(std::string value);
  212. DLL_LINKAGE JsonNode intNode(si64 value);
  213. }
  214. namespace JsonDetail
  215. {
  216. // conversion helpers for JsonNode::convertTo (partial template function instantiation is illegal in c++)
  217. template <typename T, int arithm>
  218. struct JsonConvImpl;
  219. template <typename T>
  220. struct JsonConvImpl<T, 1>
  221. {
  222. static T convertImpl(const JsonNode & node)
  223. {
  224. return T((int)node.Float());
  225. }
  226. };
  227. template <typename T>
  228. struct JsonConvImpl<T, 0>
  229. {
  230. static T convertImpl(const JsonNode & node)
  231. {
  232. return node.Float();
  233. }
  234. };
  235. template<typename Type>
  236. struct JsonConverter
  237. {
  238. static Type convert(const JsonNode & node)
  239. {
  240. ///this should be triggered only for numeric types and enums
  241. static_assert(boost::mpl::or_<std::is_arithmetic<Type>, std::is_enum<Type>, boost::is_class<Type> >::value, "Unsupported type for JsonNode::convertTo()!");
  242. return JsonConvImpl<Type, boost::mpl::or_<std::is_enum<Type>, boost::is_class<Type> >::value >::convertImpl(node);
  243. }
  244. };
  245. template<typename Type>
  246. struct JsonConverter<std::map<std::string, Type> >
  247. {
  248. static std::map<std::string, Type> convert(const JsonNode & node)
  249. {
  250. std::map<std::string, Type> ret;
  251. for (const JsonMap::value_type & entry : node.Struct())
  252. {
  253. ret.insert(entry.first, entry.second.convertTo<Type>());
  254. }
  255. return ret;
  256. }
  257. };
  258. template<typename Type>
  259. struct JsonConverter<std::set<Type> >
  260. {
  261. static std::set<Type> convert(const JsonNode & node)
  262. {
  263. std::set<Type> ret;
  264. for(const JsonVector::value_type & entry : node.Vector())
  265. {
  266. ret.insert(entry.convertTo<Type>());
  267. }
  268. return ret;
  269. }
  270. };
  271. template<typename Type>
  272. struct JsonConverter<std::vector<Type> >
  273. {
  274. static std::vector<Type> convert(const JsonNode & node)
  275. {
  276. std::vector<Type> ret;
  277. for (const JsonVector::value_type & entry: node.Vector())
  278. {
  279. ret.push_back(entry.convertTo<Type>());
  280. }
  281. return ret;
  282. }
  283. };
  284. template<>
  285. struct JsonConverter<std::string>
  286. {
  287. static std::string convert(const JsonNode & node)
  288. {
  289. return node.String();
  290. }
  291. };
  292. template<>
  293. struct JsonConverter<bool>
  294. {
  295. static bool convert(const JsonNode & node)
  296. {
  297. return node.Bool();
  298. }
  299. };
  300. }
  301. template<typename Type>
  302. Type JsonNode::convertTo() const
  303. {
  304. return JsonDetail::JsonConverter<Type>::convert(*this);
  305. }