JsonNode.h 8.2 KB

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