JsonConvertHelper.hpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  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. static bool GetJsonRootObject(Json::Value& root, const std::string& jsonTypeStr)
  236. {
  237. Json::Reader reader;
  238. if (!reader.parse(jsonTypeStr, root)) {
  239. return false;
  240. }
  241. return true;
  242. }
  243. ////////////////////////////////////////////////////////////////////////
  244. template <typename TClass, typename enable_if<HasConverFunction<TClass>::has, int>::type = 0>
  245. static inline bool Object2Json(Json::Value& jsonTypeOutValue, const std::string& key, const TClass& objValue)
  246. {
  247. std::vector<std::string> names = PreGetCustomMemberNameIfExists(objValue);
  248. if (key.empty()) {
  249. return objValue.OBJECTCONVERT2JSON_MEMEBER_REGISTER_RESERVERD_IMPLE(jsonTypeOutValue, names);
  250. } else {
  251. Json::Value jsonTypeNewValue;
  252. const bool result = objValue.OBJECTCONVERT2JSON_MEMEBER_REGISTER_RESERVERD_IMPLE(jsonTypeNewValue, names);
  253. if (result) {
  254. jsonTypeOutValue[key] = jsonTypeNewValue;
  255. }
  256. return result;
  257. }
  258. }
  259. template <typename TClass, typename enable_if<!HasConverFunction<TClass>::has, int>::type = 0>
  260. static inline bool Object2Json(Json::Value& jsonTypeOutValue, const std::string& key, const TClass& objValue)
  261. {
  262. return false;
  263. }
  264. template <typename T>
  265. static bool ParseJson(const std::vector<std::string>& names, int index, Json::Value& jsonTypeValue, const T& arg)
  266. {
  267. if (names.size() > index) {
  268. const std::string key = names[index];
  269. ///**TODO(Gifur@1/22/2022): 需要扩展其他类型实现,这里不直接用 JsonCPP 的内容,要考虑到其他自定义结构体 */
  270. return Object2Json(jsonTypeValue, key, arg);
  271. } else {
  272. return false;
  273. }
  274. }
  275. template <typename T, typename... Args>
  276. static bool ParseJson(const std::vector<std::string>& names, int index, Json::Value& jsonTypeValue, T& arg, Args&... args)
  277. {
  278. if (names.size() - (index + 0) != 1 + sizeof...(Args)) {
  279. return false;
  280. }
  281. /** 通过低柜调用实现 [Gifur@2022122]*/
  282. const std::string key = names[index];
  283. Object2Json(jsonTypeValue, key, arg);
  284. return ParseJson(names, index + 1, jsonTypeValue, args...);
  285. }
  286. /** Provider interface*/
  287. template<typename T>
  288. bool Object2Json(std::string& jsonTypeStr, const T& obj)
  289. {
  290. //std::function<Json::Value()>placehoder = [&]()->Json::Value { return Json::Value(); };
  291. //auto func = [&](std::function<Json::Value()>f) { return f(); };
  292. //Json::Value val = func(placehoder);
  293. Json::StyledWriter writer;
  294. Json::Value root;
  295. const bool result = Object2Json(root, "", obj);
  296. if (result) {
  297. jsonTypeStr = writer.write(root);
  298. }
  299. return result;
  300. }
  301. #define __func_1(func,member) func(member);
  302. #define __func_2(func,member,...) __func_1(func,member) __func_1(func,__VA_ARGS__)
  303. #define __func_3(func,member,...) __func_1(func,member) __func_2(func,__VA_ARGS__)
  304. #define __func_4(func,member,...) __func_1(func,member) __func_3(func,__VA_ARGS__)
  305. #define __func_5(func,member,...) __func_1(func,member) __func_4(func,__VA_ARGS__)
  306. //eg: COUNT(a,b,c) === 3
  307. #define COUNT(...) __count__(0, ##__VA_ARGS__, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
  308. #define __count__(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N
  309. #define __macro_cat__(a,b) a##b
  310. #define MACRO_CAT(a,b) __macro_cat__(a,b)
  311. #define FOR_EACH(func,...) \
  312. MACRO_CAT(__func_,COUNT(__VA_ARGS__))(func, __VA_ARGS__)
  313. #define JSON2OBJECT_EACH_FILED__(field) \
  314. if(!::Json2Object(field, jsonTypeValue[#field])){ \
  315. result = false; \
  316. }
  317. #endif //_SP_UTILITY_JSON_CONVERT_HELPER_