JsonNode.h 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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. /// recursivly merges source into dest, replacing identical fields
  103. /// struct : recursively calls this function
  104. /// arrays : each entry will be merged recursively
  105. /// values : value in source will replace value in dest
  106. /// null : if value in source is present but set to null it will delete entry in dest
  107. /// this function will destroy data in source
  108. DLL_LINKAGE void merge(JsonNode & dest, JsonNode & source);
  109. /// this function will preserve data stored in source by creating copy
  110. DLL_LINKAGE void mergeCopy(JsonNode & dest, JsonNode source);
  111. /**
  112. * @brief generate one Json structure from multiple files
  113. * @param files - list of filenames with parts of json structure
  114. */
  115. DLL_LINKAGE JsonNode assembleFromFiles(std::vector<std::string> files);
  116. /// removes all nodes that are identical to default entry in schema
  117. DLL_LINKAGE void minimize(JsonNode & node, const JsonNode& schema);
  118. /// check schema
  119. DLL_LINKAGE void validate(JsonNode & node, const JsonNode& schema);
  120. }
  121. //////////////////////////////////////////////////////////////////////////////////////////////////////
  122. // End of public section of the file. Anything below should be only used internally in JsonNode.cpp //
  123. //////////////////////////////////////////////////////////////////////////////////////////////////////
  124. namespace JsonDetail
  125. {
  126. // convertion helpers for JsonNode::convertTo (partial template function instantiation is illegal in c++)
  127. template<typename Type>
  128. struct JsonConverter
  129. {
  130. static Type convert(const JsonNode & node)
  131. {
  132. ///this should be triggered only for numeric types
  133. static_assert(std::is_arithmetic<Type>::value, "Unsupported type for JsonNode::convertTo()!");
  134. return node.Float();
  135. }
  136. };
  137. template<typename Type>
  138. struct JsonConverter<std::map<std::string, Type> >
  139. {
  140. static std::map<std::string, Type> convert(const JsonNode & node)
  141. {
  142. std::map<std::string, Type> ret;
  143. BOOST_FOREACH(auto entry, node.Struct())
  144. {
  145. ret.insert(entry.first, entry.second.convertTo<Type>());
  146. }
  147. return ret;
  148. }
  149. };
  150. template<typename Type>
  151. struct JsonConverter<std::set<Type> >
  152. {
  153. static std::set<Type> convert(const JsonNode & node)
  154. {
  155. std::set<Type> ret;
  156. BOOST_FOREACH(auto entry, node.Vector())
  157. {
  158. ret.insert(entry.convertTo<Type>());
  159. }
  160. return ret;
  161. }
  162. };
  163. template<typename Type>
  164. struct JsonConverter<std::vector<Type> >
  165. {
  166. static std::vector<Type> convert(const JsonNode & node)
  167. {
  168. std::vector<Type> ret;
  169. BOOST_FOREACH(auto entry, node.Vector())
  170. {
  171. ret.push_back(entry.convertTo<Type>());
  172. }
  173. return ret;
  174. }
  175. };
  176. template<>
  177. struct JsonConverter<std::string>
  178. {
  179. static std::string convert(const JsonNode & node)
  180. {
  181. return node.String();
  182. }
  183. };
  184. template<>
  185. struct JsonConverter<bool>
  186. {
  187. static bool convert(const JsonNode & node)
  188. {
  189. return node.Bool();
  190. }
  191. };
  192. class JsonWriter
  193. {
  194. //prefix for each line (tabulation)
  195. std::string prefix;
  196. std::ostream &out;
  197. public:
  198. template<typename Iterator>
  199. void writeContainer(Iterator begin, Iterator end);
  200. void writeEntry(JsonMap::const_iterator entry);
  201. void writeEntry(JsonVector::const_iterator entry);
  202. void writeString(const std::string &string);
  203. void writeNode(const JsonNode &node);
  204. JsonWriter(std::ostream &output, const JsonNode &node);
  205. };
  206. //Tiny string class that uses const char* as data for speed, members are private
  207. //for ease of debugging and some compatibility with std::string
  208. class constString
  209. {
  210. const char *data;
  211. const size_t datasize;
  212. public:
  213. constString(const char * inputString, size_t stringSize):
  214. data(inputString),
  215. datasize(stringSize)
  216. {
  217. }
  218. inline size_t size() const
  219. {
  220. return datasize;
  221. };
  222. inline const char& operator[] (size_t position)
  223. {
  224. assert (position < datasize);
  225. return data[position];
  226. }
  227. };
  228. //Internal class for string -> JsonNode conversion
  229. class JsonParser
  230. {
  231. std::string errors; // Contains description of all encountered errors
  232. constString input; // Input data
  233. ui32 lineCount; // Currently parsed line, starting from 1
  234. size_t lineStart; // Position of current line start
  235. size_t pos; // Current position of parser
  236. //Helpers
  237. bool extractEscaping(std::string &str);
  238. bool extractLiteral(const std::string &literal);
  239. bool extractString(std::string &string);
  240. bool extractWhitespace(bool verbose = true);
  241. bool extractSeparator();
  242. bool extractElement(JsonNode &node, char terminator);
  243. //Methods for extracting JSON data
  244. bool extractArray(JsonNode &node);
  245. bool extractFalse(JsonNode &node);
  246. bool extractFloat(JsonNode &node);
  247. bool extractNull(JsonNode &node);
  248. bool extractString(JsonNode &node);
  249. bool extractStruct(JsonNode &node);
  250. bool extractTrue(JsonNode &node);
  251. bool extractValue(JsonNode &node);
  252. //Add error\warning message to list
  253. bool error(const std::string &message, bool warning=false);
  254. public:
  255. JsonParser(const char * inputString, size_t stringSize, JsonNode &root);
  256. };
  257. //Internal class for Json validation, used automaticaly in JsonNode constructor. Behaviour:
  258. // - "schema" entry from root node is used for validation and will be removed
  259. // - any missing entries will be replaced with default value from schema (if present)
  260. // - if entry uses different type than defined in schema it will be removed
  261. // - entries nod described in schema will be kept unchanged
  262. class JsonValidator
  263. {
  264. std::string errors; // Contains description of all encountered errors
  265. std::list<std::string> currentPath; // path from root node to current one
  266. bool minimize;
  267. bool validateType(JsonNode &node, const JsonNode &schema, JsonNode::JsonType type);
  268. bool validateSchema(JsonNode::JsonType &type, const JsonNode &schema);
  269. bool validateNode(JsonNode &node, const JsonNode &schema, const std::string &name);
  270. bool validateItems(JsonNode &node, const JsonNode &schema);
  271. bool validateProperties(JsonNode &node, const JsonNode &schema);
  272. bool addMessage(const std::string &message);
  273. public:
  274. // validate node with "schema" entry
  275. JsonValidator(JsonNode &root, bool minimize=false);
  276. // validate with external schema
  277. JsonValidator(JsonNode &root, const JsonNode &schema, bool minimize=false);
  278. };
  279. } // namespace JsonDetail
  280. template<typename Type>
  281. Type JsonNode::convertTo() const
  282. {
  283. return JsonDetail::JsonConverter<Type>::convert(*this);
  284. }