JsonNode.h 8.7 KB

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