JsonNode.h 8.6 KB

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