JsonNode.h 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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. //Create empty node
  42. JsonNode(JsonType Type = DATA_NULL);
  43. //Create tree from Json-formatted input
  44. explicit JsonNode(const char * data, size_t datasize);
  45. //Create tree from JSON file
  46. explicit JsonNode(ResourceID && fileURI);
  47. //Copy c-tor
  48. JsonNode(const JsonNode &copy);
  49. ~JsonNode();
  50. void swap(JsonNode &b);
  51. JsonNode& operator =(JsonNode node);
  52. bool operator == (const JsonNode &other) const;
  53. bool operator != (const JsonNode &other) const;
  54. //Convert node to another type. Converting to NULL will clear all data
  55. void setType(JsonType Type);
  56. JsonType getType() const;
  57. bool isNull() const;
  58. //non-const accessors, node will change type on type mismatch
  59. bool & Bool();
  60. double & Float();
  61. std::string & String();
  62. JsonVector & Vector();
  63. JsonMap & Struct();
  64. //const accessors, will cause assertion failure on type mismatch
  65. const bool & Bool() const;
  66. const double & Float() const;
  67. const std::string & String() const;
  68. const JsonVector & Vector() const;
  69. const JsonMap & Struct() const;
  70. /// convert json tree into specified type. Json tree must have same type as Type
  71. /// Valid types: bool, string, any numeric, map and vector
  72. /// example: convertTo< std::map< std::vector<int> > >();
  73. template<typename Type>
  74. Type convertTo() const;
  75. //operator [], for structs only - get child node by name
  76. JsonNode & operator[](std::string child);
  77. const JsonNode & operator[](std::string child) const;
  78. template <typename Handler> void serialize(Handler &h, const int version)
  79. {
  80. // simple saving - save json in its string interpretation
  81. if (h.saving)
  82. {
  83. std::ostringstream stream;
  84. stream << *this;
  85. std::string str = stream.str();
  86. h & str;
  87. }
  88. else
  89. {
  90. std::string str;
  91. h & str;
  92. JsonNode(str.c_str(), str.size()).swap(*this);
  93. }
  94. }
  95. };
  96. namespace JsonUtils
  97. {
  98. DLL_LINKAGE Bonus * parseBonus (const JsonVector &ability_vec);
  99. DLL_LINKAGE Bonus * parseBonus (const JsonNode &bonus);
  100. DLL_LINKAGE void unparseBonus (JsonNode &node, const Bonus * bonus);
  101. DLL_LINKAGE void resolveIdentifier (si32 &var, const JsonNode &node, std::string name);
  102. DLL_LINKAGE void resolveIdentifier (const JsonNode &node, si32 &var);
  103. /// recursivly merges source into dest, replacing identical fields
  104. /// struct : recursively calls this function
  105. /// arrays : each entry will be merged recursively
  106. /// values : value in source will replace value in dest
  107. /// null : if value in source is present but set to null it will delete entry in dest
  108. /// this function will destroy data in source
  109. DLL_LINKAGE void merge(JsonNode & dest, JsonNode & source);
  110. /// this function will preserve data stored in source by creating copy
  111. DLL_LINKAGE void mergeCopy(JsonNode & dest, JsonNode source);
  112. /**
  113. * @brief generate one Json structure from multiple files
  114. * @param files - list of filenames with parts of json structure
  115. */
  116. DLL_LINKAGE JsonNode assembleFromFiles(std::vector<std::string> files);
  117. /// removes all nodes that are identical to default entry in schema
  118. DLL_LINKAGE void minimize(JsonNode & node, const JsonNode& schema);
  119. /// check schema
  120. DLL_LINKAGE void validate(JsonNode & node, const JsonNode& schema);
  121. }
  122. //////////////////////////////////////////////////////////////////////////////////////////////////////
  123. // End of public section of the file. Anything below should be only used internally in JsonNode.cpp //
  124. //////////////////////////////////////////////////////////////////////////////////////////////////////
  125. namespace JsonDetail
  126. {
  127. // convertion helpers for JsonNode::convertTo (partial template function instantiation is illegal in c++)
  128. template <typename T, int arithm>
  129. struct JsonConvImpl;
  130. template <typename T>
  131. struct JsonConvImpl<T, 1>
  132. {
  133. static T convertImpl(const JsonNode & node)
  134. {
  135. return T((int)node.Float());
  136. }
  137. };
  138. template <typename T>
  139. struct JsonConvImpl<T, 0>
  140. {
  141. static T convertImpl(const JsonNode & node)
  142. {
  143. return node.Float();
  144. }
  145. };
  146. template<typename Type>
  147. struct JsonConverter
  148. {
  149. static Type convert(const JsonNode & node)
  150. {
  151. ///this should be triggered only for numeric types and enums
  152. static_assert(boost::mpl::or_<std::is_arithmetic<Type>, std::is_enum<Type>, boost::is_class<Type> >::value, "Unsupported type for JsonNode::convertTo()!");
  153. return JsonConvImpl<Type, boost::mpl::or_<std::is_enum<Type>, boost::is_class<Type> >::value >::convertImpl(node);
  154. }
  155. };
  156. template<typename Type>
  157. struct JsonConverter<std::map<std::string, Type> >
  158. {
  159. static std::map<std::string, Type> convert(const JsonNode & node)
  160. {
  161. std::map<std::string, Type> ret;
  162. BOOST_FOREACH(auto entry, node.Struct())
  163. {
  164. ret.insert(entry.first, entry.second.convertTo<Type>());
  165. }
  166. return ret;
  167. }
  168. };
  169. template<typename Type>
  170. struct JsonConverter<std::set<Type> >
  171. {
  172. static std::set<Type> convert(const JsonNode & node)
  173. {
  174. std::set<Type> ret;
  175. BOOST_FOREACH(auto entry, node.Vector())
  176. {
  177. ret.insert(entry.convertTo<Type>());
  178. }
  179. return ret;
  180. }
  181. };
  182. template<typename Type>
  183. struct JsonConverter<std::vector<Type> >
  184. {
  185. static std::vector<Type> convert(const JsonNode & node)
  186. {
  187. std::vector<Type> ret;
  188. BOOST_FOREACH(auto entry, node.Vector())
  189. {
  190. ret.push_back(entry.convertTo<Type>());
  191. }
  192. return ret;
  193. }
  194. };
  195. template<>
  196. struct JsonConverter<std::string>
  197. {
  198. static std::string convert(const JsonNode & node)
  199. {
  200. return node.String();
  201. }
  202. };
  203. template<>
  204. struct JsonConverter<bool>
  205. {
  206. static bool convert(const JsonNode & node)
  207. {
  208. return node.Bool();
  209. }
  210. };
  211. class JsonWriter
  212. {
  213. //prefix for each line (tabulation)
  214. std::string prefix;
  215. std::ostream &out;
  216. public:
  217. template<typename Iterator>
  218. void writeContainer(Iterator begin, Iterator end);
  219. void writeEntry(JsonMap::const_iterator entry);
  220. void writeEntry(JsonVector::const_iterator entry);
  221. void writeString(const std::string &string);
  222. void writeNode(const JsonNode &node);
  223. JsonWriter(std::ostream &output, const JsonNode &node);
  224. };
  225. //Tiny string class that uses const char* as data for speed, members are private
  226. //for ease of debugging and some compatibility with std::string
  227. class constString
  228. {
  229. const char *data;
  230. const size_t datasize;
  231. public:
  232. constString(const char * inputString, size_t stringSize):
  233. data(inputString),
  234. datasize(stringSize)
  235. {
  236. }
  237. inline size_t size() const
  238. {
  239. return datasize;
  240. };
  241. inline const char& operator[] (size_t position)
  242. {
  243. assert (position < datasize);
  244. return data[position];
  245. }
  246. };
  247. //Internal class for string -> JsonNode conversion
  248. class JsonParser
  249. {
  250. std::string errors; // Contains description of all encountered errors
  251. constString input; // Input data
  252. ui32 lineCount; // Currently parsed line, starting from 1
  253. size_t lineStart; // Position of current line start
  254. size_t pos; // Current position of parser
  255. //Helpers
  256. bool extractEscaping(std::string &str);
  257. bool extractLiteral(const std::string &literal);
  258. bool extractString(std::string &string);
  259. bool extractWhitespace(bool verbose = true);
  260. bool extractSeparator();
  261. bool extractElement(JsonNode &node, char terminator);
  262. //Methods for extracting JSON data
  263. bool extractArray(JsonNode &node);
  264. bool extractFalse(JsonNode &node);
  265. bool extractFloat(JsonNode &node);
  266. bool extractNull(JsonNode &node);
  267. bool extractString(JsonNode &node);
  268. bool extractStruct(JsonNode &node);
  269. bool extractTrue(JsonNode &node);
  270. bool extractValue(JsonNode &node);
  271. //Add error\warning message to list
  272. bool error(const std::string &message, bool warning=false);
  273. public:
  274. JsonParser(const char * inputString, size_t stringSize, JsonNode &root);
  275. };
  276. //Internal class for Json validation, used automaticaly in JsonNode constructor. Behaviour:
  277. // - "schema" entry from root node is used for validation and will be removed
  278. // - any missing entries will be replaced with default value from schema (if present)
  279. // - if entry uses different type than defined in schema it will be removed
  280. // - entries nod described in schema will be kept unchanged
  281. class JsonValidator
  282. {
  283. std::string errors; // Contains description of all encountered errors
  284. std::list<std::string> currentPath; // path from root node to current one
  285. bool minimize;
  286. bool validateType(JsonNode &node, const JsonNode &schema, JsonNode::JsonType type);
  287. bool validateSchema(JsonNode::JsonType &type, const JsonNode &schema);
  288. bool validateNode(JsonNode &node, const JsonNode &schema, const std::string &name);
  289. bool validateItems(JsonNode &node, const JsonNode &schema);
  290. bool validateProperties(JsonNode &node, const JsonNode &schema);
  291. bool addMessage(const std::string &message);
  292. public:
  293. // validate node with "schema" entry
  294. JsonValidator(JsonNode &root, bool minimize=false);
  295. // validate with external schema
  296. JsonValidator(JsonNode &root, const JsonNode &schema, bool minimize=false);
  297. };
  298. } // namespace JsonDetail
  299. template<typename Type>
  300. Type JsonNode::convertTo() const
  301. {
  302. return JsonDetail::JsonConverter<Type>::convert(*this);
  303. }