JsonNode.h 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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. //removes all nodes that are identical to default entry in schema
  46. void minimize(const JsonNode& schema);
  47. //check schema
  48. void validate(const JsonNode& schema);
  49. //Convert node to another type. Converting to NULL will clear all data
  50. void setType(JsonType Type);
  51. JsonType getType() const;
  52. bool isNull() const;
  53. //non-const accessors, node will change type on type mismatch
  54. bool & Bool();
  55. double & Float();
  56. std::string & String();
  57. JsonVector & Vector();
  58. JsonMap & Struct();
  59. //const accessors, will cause assertion failure on type mismatch
  60. const bool & Bool() const;
  61. const double & Float() const;
  62. const std::string & String() const;
  63. const JsonVector & Vector() const;
  64. const JsonMap & Struct() const;
  65. template<typename T>
  66. std::vector<T> StdVector() const;
  67. //operator [], for structs only - get child node by name
  68. JsonNode & operator[](std::string child);
  69. const JsonNode & operator[](std::string child) const;
  70. //error value for const operator[]
  71. static const JsonNode nullNode;
  72. /// recursivly merges source into dest, replacing identical fields
  73. /// struct : recursively calls this function
  74. /// arrays : append array in dest with data from source
  75. /// values : value in source will replace value in dest
  76. /// null : if value in source is present but set to null it will delete entry in dest
  77. /// this function will destroy data in source
  78. static void merge(JsonNode & dest, JsonNode & source);
  79. /// this function will preserve data stored in source by creating copy
  80. static void mergeCopy(JsonNode & dest, JsonNode source);
  81. template <typename Handler> void serialize(Handler &h, const int version)
  82. {
  83. if (h.saving)
  84. {
  85. std::ostringstream stream;
  86. stream << *this;
  87. std::string str = stream.str();
  88. h & str;
  89. }
  90. else
  91. {
  92. std::string str;
  93. h & str;
  94. JsonNode(str.c_str(), str.size()).swap(*this);
  95. }
  96. }
  97. };
  98. template<>
  99. inline std::vector<std::string> JsonNode::StdVector() const
  100. {
  101. std::vector<std::string> ret;
  102. BOOST_FOREACH(const JsonNode &node, Vector())
  103. {
  104. ret.push_back(node.String());
  105. }
  106. return ret;
  107. }
  108. template<typename T>
  109. std::vector<T> JsonNode::StdVector() const
  110. {
  111. static_assert(std::is_arithmetic<T>::value, "This works with numbers only.");
  112. std::vector<T> ret;
  113. BOOST_FOREACH(const JsonNode &node, Vector())
  114. {
  115. ret.push_back(node.Float());
  116. }
  117. return ret;
  118. }
  119. class JsonWriter
  120. {
  121. //prefix for each line (tabulation)
  122. std::string prefix;
  123. std::ostream &out;
  124. public:
  125. template<typename Iterator>
  126. void writeContainer(Iterator begin, Iterator end);
  127. void writeEntry(JsonMap::const_iterator entry);
  128. void writeEntry(JsonVector::const_iterator entry);
  129. void writeString(const std::string &string);
  130. void writeNode(const JsonNode &node);
  131. JsonWriter(std::ostream &output, const JsonNode &node);
  132. };
  133. //Tiny string class that uses const char* as data for speed, members are private
  134. //for ease of debugging and some compatibility with std::string
  135. class constString
  136. {
  137. const char *data;
  138. const size_t datasize;
  139. public:
  140. constString(const char * inputString, size_t stringSize):
  141. data(inputString),
  142. datasize(stringSize)
  143. {
  144. }
  145. inline size_t size() const
  146. {
  147. return datasize;
  148. };
  149. inline const char& operator[] (size_t position)
  150. {
  151. assert (position < datasize);
  152. return data[position];
  153. }
  154. };
  155. //Internal class for string -> JsonNode conversion
  156. class JsonParser
  157. {
  158. std::string errors; // Contains description of all encountered errors
  159. constString input; // Input data
  160. ui32 lineCount; // Currently parsed line, starting from 1
  161. size_t lineStart; // Position of current line start
  162. size_t pos; // Current position of parser
  163. //Helpers
  164. bool extractEscaping(std::string &str);
  165. bool extractLiteral(const std::string &literal);
  166. bool extractString(std::string &string);
  167. bool extractWhitespace(bool verbose = true);
  168. bool extractSeparator();
  169. bool extractElement(JsonNode &node, char terminator);
  170. //Methods for extracting JSON data
  171. bool extractArray(JsonNode &node);
  172. bool extractFalse(JsonNode &node);
  173. bool extractFloat(JsonNode &node);
  174. bool extractNull(JsonNode &node);
  175. bool extractString(JsonNode &node);
  176. bool extractStruct(JsonNode &node);
  177. bool extractTrue(JsonNode &node);
  178. bool extractValue(JsonNode &node);
  179. //Add error\warning message to list
  180. bool error(const std::string &message, bool warning=false);
  181. public:
  182. JsonParser(const char * inputString, size_t stringSize, JsonNode &root);
  183. };
  184. //Internal class for Json validation, used automaticaly in JsonNode constructor. Behaviour:
  185. // - "schema" entry from root node is used for validation and will be removed
  186. // - any missing entries will be replaced with default value from schema (if present)
  187. // - if entry uses different type than defined in schema it will be removed
  188. // - entries nod described in schema will be kept unchanged
  189. class JsonValidator
  190. {
  191. std::string errors; // Contains description of all encountered errors
  192. std::list<std::string> currentPath; // path from root node to current one
  193. bool minimize;
  194. bool validateType(JsonNode &node, const JsonNode &schema, JsonNode::JsonType type);
  195. bool validateSchema(JsonNode::JsonType &type, const JsonNode &schema);
  196. bool validateNode(JsonNode &node, const JsonNode &schema, const std::string &name);
  197. bool validateItems(JsonNode &node, const JsonNode &schema);
  198. bool validateProperties(JsonNode &node, const JsonNode &schema);
  199. bool addMessage(const std::string &message);
  200. public:
  201. // validate node with "schema" entry
  202. JsonValidator(JsonNode &root, bool minimize=false);
  203. // validate with external schema
  204. JsonValidator(JsonNode &root, const JsonNode &schema, bool minimize=false);
  205. };
  206. DLL_LINKAGE Bonus * ParseBonus (const JsonVector &ability_vec);
  207. DLL_LINKAGE Bonus * ParseBonus (const JsonNode &bonus);
  208. DLL_LINKAGE void UnparseBonus (JsonNode &node, const Bonus * bonus);