JsonNode.h 8.5 KB

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