JsonConvertHelper.hpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. #ifndef _SP_UTILITY_JSON_CONVERT_HELPER_
  2. #define _SP_UTILITY_JSON_CONVERT_HELPER_
  3. #include "json/json.h"
  4. #include <string>
  5. #include <vector>
  6. #include <initializer_list>
  7. #define JSONCONVERT2OBJECT_MEMEBER_REGISTER(...) \
  8. bool JSONCONVERT2OBJECT_MEMEBER_REGISTER_RESERVERD_IMPLE(const Json::Value& jsonTypeValue, std::vector<std::string> &names) \
  9. { \
  10. if(names.size() <= 0) { \
  11. names = Member2KeyParseWithStr(#__VA_ARGS__); \
  12. } \
  13. return JsonParse(names, 0, jsonTypeValue, __VA_ARGS__); \
  14. } \
  15. bool OBJECTCONVERT2JSON_MEMEBER_REGISTER_RESERVERD_IMPLE(Json::Value& jsonTypeValue, std::vector<std::string> &names) const \
  16. { \
  17. if(names.size() <= 0) { \
  18. names = Member2KeyParseWithStr(#__VA_ARGS__); \
  19. } \
  20. return ParseJson(names, 0, jsonTypeValue, __VA_ARGS__); \
  21. } \
  22. #define JSONCONVERT2OBJECT_MEMEBER_RENAME_REGISTER(...) \
  23. std::vector<std::string> JSONCONVERT2OBJECT_MEMEBER_RENAME_REGISTER_RESERVERD_IMPLE() const \
  24. { \
  25. return Member2KeyParseWithMultiParam({ __VA_ARGS__ }); \
  26. }
  27. template <bool, class TYPE = void>
  28. struct enable_if
  29. {
  30. };
  31. template <class TYPE>
  32. struct enable_if<true, TYPE>
  33. {
  34. typedef TYPE type;
  35. };
  36. template <typename T>
  37. struct HasConverFunction
  38. {
  39. template <typename TT>
  40. static char func(decltype(&TT::JSONCONVERT2OBJECT_MEMEBER_REGISTER_RESERVERD_IMPLE)); //@1
  41. template <typename TT>
  42. static int func(...); //@2
  43. /*
  44. * 如果类型T没有 JSONCONVERT2OBJECT_MEMEBER_REGISTER_RESERVERD_IMPLE 方法,
  45. * func<T>(NULL) 匹配 @1 时会产生错误,由于 SFINAE 准则,只能匹配@2
  46. * 的func,此时返回值 4 个字节,has 变量为 false,反之,has 变量为 true
  47. */
  48. const static bool has = (sizeof(func<T>(NULL)) == sizeof(char));
  49. template <typename TT>
  50. static char func2(decltype(&TT::JSONCONVERT2OBJECT_MEMEBER_RENAME_REGISTER_RESERVERD_IMPLE)); //@1
  51. template <typename TT>
  52. static int func2(...); //@2
  53. const static bool has2 = (sizeof(func2<T>(NULL)) == sizeof(char));
  54. };
  55. static std::vector<std::string> Member2KeyParseWithMultiParam(std::initializer_list<std::string> il)
  56. {
  57. std::vector<std::string> result;
  58. for (auto it = il.begin(); it != il.end(); it++) {
  59. result.push_back(*it);
  60. }
  61. return result;
  62. }
  63. inline static std::string NormalStringTrim(std::string const& str)
  64. {
  65. static char const* whitespaceChars = "\n\r\t ";
  66. std::string::size_type start = str.find_first_not_of(whitespaceChars);
  67. std::string::size_type end = str.find_last_not_of(whitespaceChars);
  68. return start != std::string::npos ? str.substr(start, 1 + end - start) : std::string();
  69. }
  70. inline static std::vector<std::string> NormalStringSplit(std::string str, char splitElem)
  71. {
  72. std::vector<std::string> strs;
  73. std::string::size_type pos1, pos2;
  74. pos2 = str.find(splitElem);
  75. pos1 = 0;
  76. while (std::string::npos != pos2) {
  77. strs.push_back(str.substr(pos1, pos2 - pos1));
  78. pos1 = pos2 + 1;
  79. pos2 = str.find(splitElem, pos1);
  80. }
  81. strs.push_back(str.substr(pos1));
  82. return strs;
  83. }
  84. static std::vector<std::string> Member2KeyParseWithStr(const std::string& values)
  85. {
  86. std::vector<std::string> result;
  87. auto enumValues = NormalStringSplit(values, ',');
  88. result.reserve(enumValues.size());
  89. for (auto const& enumValue : enumValues) {
  90. /** 修复喜欢加空格或代码格式化导致的问题 [Gifur@2022122]*/
  91. result.push_back(NormalStringTrim(enumValue));
  92. }
  93. return result;
  94. }
  95. //////////////////////////////////////////////////////////////////////////////
  96. static bool Json2Object(bool& aimObj, const Json::Value& jsonTypeValue)
  97. {
  98. if (jsonTypeValue.isNull() || !jsonTypeValue.isBool()) {
  99. return false;
  100. } else {
  101. aimObj = jsonTypeValue.asBool();
  102. return true;
  103. }
  104. }
  105. static bool Object2Json(Json::Value& jsonTypeValue, const std::string& key, bool value)
  106. {
  107. jsonTypeValue[key] = value;
  108. return true;
  109. }
  110. static bool Json2Object(int& aimObj, const Json::Value& jsonTypeValue)
  111. {
  112. if (jsonTypeValue.isNull() || !jsonTypeValue.isInt()) {
  113. return false;
  114. } else {
  115. aimObj = jsonTypeValue.asInt();
  116. return true;
  117. }
  118. }
  119. static bool Object2Json(Json::Value& jsonTypeValue, const std::string& key, const int& value)
  120. {
  121. jsonTypeValue[key] = value;
  122. return true;
  123. }
  124. static bool Json2Object(unsigned int& aimObj, const Json::Value& jsonTypeValue)
  125. {
  126. if (jsonTypeValue.isNull() || !jsonTypeValue.isUInt()) {
  127. return false;
  128. } else {
  129. aimObj = jsonTypeValue.asUInt();
  130. return true;
  131. }
  132. }
  133. static bool Object2Json(Json::Value& jsonTypeValue, const std::string& key, const unsigned int& value)
  134. {
  135. jsonTypeValue[key] = value;
  136. return true;
  137. }
  138. static bool Json2Object(double& aimObj, const Json::Value& jsonTypeValue)
  139. {
  140. if (jsonTypeValue.isNull() || !jsonTypeValue.isDouble()) {
  141. return false;
  142. } else {
  143. aimObj = jsonTypeValue.asDouble();
  144. return true;
  145. }
  146. }
  147. static bool Object2Json(Json::Value& jsonTypeValue, const std::string& key, const double& value)
  148. {
  149. jsonTypeValue[key] = value;
  150. return true;
  151. }
  152. static bool Json2Object(std::string& aimObj, const Json::Value& jsonTypeValue)
  153. {
  154. if (jsonTypeValue.isNull() || !jsonTypeValue.isString()) {
  155. return false;
  156. } else {
  157. aimObj = jsonTypeValue.asString();
  158. return true;
  159. }
  160. }
  161. static bool Object2Json(Json::Value& jsonTypeValue, const std::string& key, const std::string& value)
  162. {
  163. jsonTypeValue[key] = value;
  164. return true;
  165. }
  166. template <typename TClass, typename enable_if<HasConverFunction<TClass>::has2, int>::type = 0>
  167. static inline std::vector<std::string> PreGetCustomMemberNameIfExists(const TClass& aimObj)
  168. {
  169. return aimObj.JSONCONVERT2OBJECT_MEMEBER_RENAME_REGISTER_RESERVERD_IMPLE();
  170. }
  171. template <typename TClass, typename enable_if<!HasConverFunction<TClass>::has2, int>::type = 0>
  172. static inline std::vector<std::string> PreGetCustomMemberNameIfExists(const TClass& aimObj)
  173. {
  174. return std::vector<std::string>();
  175. }
  176. template <typename TClass, typename enable_if<HasConverFunction<TClass>::has, int>::type = 0>
  177. static inline bool Json2Object(TClass& aimObj, const Json::Value& jsonTypeValue)
  178. {
  179. std::vector<std::string> names = PreGetCustomMemberNameIfExists(aimObj);
  180. return aimObj.JSONCONVERT2OBJECT_MEMEBER_REGISTER_RESERVERD_IMPLE(jsonTypeValue, names);
  181. }
  182. template <typename TClass, typename enable_if<!HasConverFunction<TClass>::has, int>::type = 0>
  183. static inline bool Json2Object(TClass& aimObj, const Json::Value& jsonTypeValue)
  184. {
  185. return false;
  186. }
  187. template <typename T>
  188. static bool Json2Object(std::vector<T>& aimObj, const Json::Value& jsonTypeValue)
  189. {
  190. if (jsonTypeValue.isNull() || !jsonTypeValue.isArray()) {
  191. return false;
  192. } else {
  193. aimObj.clear();
  194. bool result(true);
  195. for (int i = 0; i < jsonTypeValue.size(); ++i) {
  196. T item;
  197. if (!Json2Object(item, jsonTypeValue[i])) {
  198. result = false;
  199. }
  200. aimObj.push_back(item);
  201. }
  202. return result;
  203. }
  204. }
  205. template <typename T>
  206. static bool JsonParse(const std::vector<std::string>& names, int index, const Json::Value& jsonTypeValue, T& arg)
  207. {
  208. const auto key = names[index];
  209. if (!jsonTypeValue.isMember(key) || Json2Object(arg, jsonTypeValue[key])) {
  210. return true;
  211. } else {
  212. return false;
  213. }
  214. }
  215. template <typename T, typename... Args>
  216. static bool JsonParse(const std::vector<std::string>& names, int index, const Json::Value& jsonTypeValue, T& arg, Args&... args)
  217. {
  218. if (!JsonParse(names, index, jsonTypeValue, arg)) {
  219. return false;
  220. } else {
  221. return JsonParse(names, index + 1, jsonTypeValue, args...);
  222. }
  223. }
  224. /** Provider interface*/
  225. template<typename TClass>
  226. bool Json2Object(TClass& aimObj, const std::string& jsonTypeStr)
  227. {
  228. Json::Reader reader;
  229. Json::Value root;
  230. if (!reader.parse(jsonTypeStr, root) || root.isNull()) {
  231. return false;
  232. }
  233. return Json2Object(aimObj, root);
  234. }
  235. ////////////////////////////////////////////////////////////////////////
  236. template <typename TClass, typename enable_if<HasConverFunction<TClass>::has, int>::type = 0>
  237. static inline bool Object2Json(Json::Value& jsonTypeOutValue, const std::string& key, const TClass& objValue)
  238. {
  239. std::vector<std::string> names = PreGetCustomMemberNameIfExists(objValue);
  240. if (key.empty()) {
  241. return objValue.OBJECTCONVERT2JSON_MEMEBER_REGISTER_RESERVERD_IMPLE(jsonTypeOutValue, names);
  242. } else {
  243. Json::Value jsonTypeNewValue;
  244. const bool result = objValue.OBJECTCONVERT2JSON_MEMEBER_REGISTER_RESERVERD_IMPLE(jsonTypeNewValue, names);
  245. if (result) {
  246. jsonTypeOutValue[key] = jsonTypeNewValue;
  247. }
  248. return result;
  249. }
  250. }
  251. template <typename TClass, typename enable_if<!HasConverFunction<TClass>::has, int>::type = 0>
  252. static inline bool Object2Json(Json::Value& jsonTypeOutValue, const std::string& key, const TClass& objValue)
  253. {
  254. return false;
  255. }
  256. template <typename T>
  257. static bool ParseJson(const std::vector<std::string>& names, int index, Json::Value& jsonTypeValue, const T& arg)
  258. {
  259. if (names.size() > index) {
  260. const std::string key = names[index];
  261. ///**TODO(Gifur@1/22/2022): 需要扩展其他类型实现,这里不直接用 JsonCPP 的内容,要考虑到其他自定义结构体 */
  262. return Object2Json(jsonTypeValue, key, arg);
  263. } else {
  264. return false;
  265. }
  266. }
  267. template <typename T, typename... Args>
  268. static bool ParseJson(const std::vector<std::string>& names, int index, Json::Value& jsonTypeValue, T& arg, Args&... args)
  269. {
  270. if (names.size() - (index + 0) != 1 + sizeof...(Args)) {
  271. return false;
  272. }
  273. /** 通过低柜调用实现 [Gifur@2022122]*/
  274. const std::string key = names[index];
  275. Object2Json(jsonTypeValue, key, arg);
  276. return ParseJson(names, index + 1, jsonTypeValue, args...);
  277. }
  278. /** Provider interface*/
  279. template<typename T>
  280. bool Object2Json(std::string& jsonTypeStr, const T& obj)
  281. {
  282. //std::function<Json::Value()>placehoder = [&]()->Json::Value { return Json::Value(); };
  283. //auto func = [&](std::function<Json::Value()>f) { return f(); };
  284. //Json::Value val = func(placehoder);
  285. Json::StyledWriter writer;
  286. Json::Value root;
  287. const bool result = Object2Json(root, "", obj);
  288. if (result) {
  289. jsonTypeStr = writer.write(root);
  290. }
  291. return result;
  292. }
  293. #define __func_1(func,member) func(member);
  294. #define __func_2(func,member,...) __func_1(func,member) __func_1(func,__VA_ARGS__)
  295. #define __func_3(func,member,...) __func_1(func,member) __func_2(func,__VA_ARGS__)
  296. #define __func_4(func,member,...) __func_1(func,member) __func_3(func,__VA_ARGS__)
  297. #define __func_5(func,member,...) __func_1(func,member) __func_4(func,__VA_ARGS__)
  298. //eg: COUNT(a,b,c) === 3
  299. #define COUNT(...) __count__(0, ##__VA_ARGS__, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
  300. #define __count__(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N
  301. #define __macro_cat__(a,b) a##b
  302. #define MACRO_CAT(a,b) __macro_cat__(a,b)
  303. #define FOR_EACH(func,...) \
  304. MACRO_CAT(__func_,COUNT(__VA_ARGS__))(func, __VA_ARGS__)
  305. #define JSON2OBJECT_EACH_FILED__(field) \
  306. if(!::Json2Object(field, jsonTypeValue[#field])){ \
  307. result = false; \
  308. }
  309. #endif //_SP_UTILITY_JSON_CONVERT_HELPER_