JsonConvertHelper.hpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  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. typedef BYTE byte, *PBYTE, *LPBYTE;
  8. struct ByteData
  9. {
  10. BYTE bData[4096];
  11. };
  12. static int StrBuf2HexBuf(const char* strBuf, PBYTE* hexBuf)
  13. {
  14. int len = strlen(strBuf);
  15. if (len == 0 || len % 2 != 0)
  16. return 0;
  17. BYTE* buf = new BYTE[len / 2];
  18. if (buf == NULL)
  19. return 0;
  20. int j = 0;
  21. for (int i = 0; i < len;) {
  22. int tmpVal;
  23. sscanf(strBuf + i, "%2X", &tmpVal);
  24. buf[j] = tmpVal;
  25. i += 2;
  26. j++;
  27. }
  28. *hexBuf = buf;
  29. return j;
  30. }
  31. #define JSONCONVERT2OBJECT_MEMEBER_REGISTER(...) \
  32. bool JSONCONVERT2OBJECT_MEMEBER_REGISTER_RESERVERD_IMPLE(const Json::Value& jsonTypeValue, std::vector<std::string> &names) \
  33. { \
  34. if(names.size() <= 0) { \
  35. names = Member2KeyParseWithStr(#__VA_ARGS__); \
  36. } \
  37. return JsonParse(names, 0, jsonTypeValue, __VA_ARGS__); \
  38. } \
  39. bool OBJECTCONVERT2JSON_MEMEBER_REGISTER_RESERVERD_IMPLE(Json::Value& jsonTypeValue, std::vector<std::string> &names) const \
  40. { \
  41. if(names.size() <= 0) { \
  42. names = Member2KeyParseWithStr(#__VA_ARGS__); \
  43. } \
  44. return ParseJson(names, 0, jsonTypeValue, __VA_ARGS__); \
  45. }
  46. /*
  47. std::string GetOutputString() const\
  48. { \
  49. std::ostringstream str; \
  50. std::vector<std::string> names = Member2KeyParseWithStr(#__VA_ARGS__); \
  51. for(auto it=names.begin(); it!=names.end(); ++it) { if(it != names.begin()) { str << " | "; } str << *it; } \
  52. if (names.size() > 0) { str << "\r\n"; } \
  53. DbgPrint(str, __VA_ARGS__); \
  54. return str.str(); \
  55. }
  56. */
  57. #define JSONCONVERT2OBJECT_MEMEBER_RENAME_REGISTER(...) \
  58. std::vector<std::string> JSONCONVERT2OBJECT_MEMEBER_RENAME_REGISTER_RESERVERD_IMPLE() const \
  59. { \
  60. return Member2KeyParseWithMultiParam({ __VA_ARGS__ }); \
  61. }
  62. namespace SP
  63. {
  64. namespace Utility
  65. {
  66. namespace JSON
  67. {
  68. template <bool, class TYPE = void>
  69. struct enable_if
  70. {
  71. };
  72. template <class TYPE>
  73. struct enable_if<true, TYPE>
  74. {
  75. typedef TYPE type;
  76. };
  77. } //JSON
  78. } //Utility
  79. } //SP
  80. template <typename T>
  81. struct HasConverFunction
  82. {
  83. template <typename TT>
  84. static char func(decltype(&TT::JSONCONVERT2OBJECT_MEMEBER_REGISTER_RESERVERD_IMPLE)); //@1
  85. template <typename TT>
  86. static int func(...); //@2
  87. /*
  88. * 如果类型T没有 JSONCONVERT2OBJECT_MEMEBER_REGISTER_RESERVERD_IMPLE 方法,
  89. * func<T>(NULL) 匹配 @1 时会产生错误,由于 SFINAE 准则,只能匹配@2
  90. * 的func,此时返回值 4 个字节,has 变量为 false,反之,has 变量为 true
  91. */
  92. const static bool has = (sizeof(func<T>(NULL)) == sizeof(char));
  93. template <typename TT>
  94. static char func2(decltype(&TT::JSONCONVERT2OBJECT_MEMEBER_RENAME_REGISTER_RESERVERD_IMPLE)); //@1
  95. template <typename TT>
  96. static int func2(...); //@2
  97. const static bool has2 = (sizeof(func2<T>(NULL)) == sizeof(char));
  98. };
  99. static std::vector<std::string> Member2KeyParseWithMultiParam(std::initializer_list<std::string> il)
  100. {
  101. std::vector<std::string> result;
  102. for (auto it = il.begin(); it != il.end(); it++) {
  103. result.push_back(*it);
  104. }
  105. return result;
  106. }
  107. inline static std::string NormalStringTrim(std::string const& str)
  108. {
  109. static char const* whitespaceChars = "\n\r\t ";
  110. std::string::size_type start = str.find_first_not_of(whitespaceChars);
  111. std::string::size_type end = str.find_last_not_of(whitespaceChars);
  112. return start != std::string::npos ? str.substr(start, 1 + end - start) : std::string();
  113. }
  114. inline static std::vector<std::string> NormalStringSplit(std::string str, char splitElem)
  115. {
  116. std::vector<std::string> strs;
  117. std::string::size_type pos1, pos2;
  118. pos2 = str.find(splitElem);
  119. pos1 = 0;
  120. while (std::string::npos != pos2) {
  121. strs.push_back(str.substr(pos1, pos2 - pos1));
  122. pos1 = pos2 + 1;
  123. pos2 = str.find(splitElem, pos1);
  124. }
  125. strs.push_back(str.substr(pos1));
  126. return strs;
  127. }
  128. static std::vector<std::string> Member2KeyParseWithStr(const std::string& values)
  129. {
  130. std::vector<std::string> result;
  131. auto enumValues = NormalStringSplit(values, ',');
  132. result.reserve(enumValues.size());
  133. for (auto const& enumValue : enumValues) {
  134. /** 修复喜欢加空格或代码格式化导致的问题 [Gifur@2022122]*/
  135. result.push_back(NormalStringTrim(enumValue));
  136. }
  137. return result;
  138. }
  139. //////////////////////////////////////////////////////////////////////////////
  140. static bool Json2Object(bool& aimObj, const Json::Value& jsonTypeValue)
  141. {
  142. if (jsonTypeValue.isNull()) {
  143. aimObj = false;
  144. return true;
  145. }
  146. if (jsonTypeValue.isNull() || !jsonTypeValue.isBool()) {
  147. return false;
  148. } else {
  149. aimObj = jsonTypeValue.asBool();
  150. return true;
  151. }
  152. }
  153. static bool Object2Json(Json::Value& jsonTypeValue, const std::string& key, bool value)
  154. {
  155. jsonTypeValue[key] = value;
  156. return true;
  157. }
  158. static bool Json2Object(int& aimObj, const Json::Value& jsonTypeValue)
  159. {
  160. if (jsonTypeValue.isNull()) {
  161. aimObj = 0;
  162. return true;
  163. }
  164. if (jsonTypeValue.isNull() || !jsonTypeValue.isInt()) {
  165. return false;
  166. } else {
  167. aimObj = jsonTypeValue.asInt();
  168. return true;
  169. }
  170. }
  171. static bool Object2Json(Json::Value& jsonTypeValue, const std::string& key, const int& value)
  172. {
  173. jsonTypeValue[key] = value;
  174. return true;
  175. }
  176. static bool Json2Object(unsigned int& aimObj, const Json::Value& jsonTypeValue)
  177. {
  178. if (jsonTypeValue.isNull()) {
  179. aimObj = 0;
  180. return true;
  181. }
  182. if (jsonTypeValue.isNull() || !jsonTypeValue.isUInt()) {
  183. return false;
  184. } else {
  185. aimObj = jsonTypeValue.asUInt();
  186. return true;
  187. }
  188. }
  189. static bool Object2Json(Json::Value& jsonTypeValue, const std::string& key, const unsigned int& value)
  190. {
  191. jsonTypeValue[key] = value;
  192. return true;
  193. }
  194. static bool Json2Object(double& aimObj, const Json::Value& jsonTypeValue)
  195. {
  196. if (jsonTypeValue.isNull()) {
  197. aimObj = 0.0;
  198. return true;
  199. }
  200. if (jsonTypeValue.isNull() || !jsonTypeValue.isDouble()) {
  201. return false;
  202. } else {
  203. aimObj = jsonTypeValue.asDouble();
  204. return true;
  205. }
  206. }
  207. static bool Object2Json(Json::Value& jsonTypeValue, const std::string& key, const double& value)
  208. {
  209. jsonTypeValue[key] = value;
  210. return true;
  211. }
  212. static bool Json2Object(std::string& aimObj, const Json::Value& jsonTypeValue)
  213. {
  214. if (jsonTypeValue.isNull()) {
  215. aimObj.clear();
  216. return true;
  217. }
  218. if (jsonTypeValue.isNull() || !jsonTypeValue.isString()) {
  219. return false;
  220. } else {
  221. aimObj = jsonTypeValue.asString();
  222. return true;
  223. }
  224. }
  225. static bool Object2Json(Json::Value& jsonTypeValue, const std::string& key, const std::string& value)
  226. {
  227. jsonTypeValue[key] = value;
  228. return true;
  229. }
  230. static bool Json2Object(ByteData& aimObj, const Json::Value& jsonTypeValue)
  231. {
  232. PBYTE tmp = new BYTE[4096];
  233. if (jsonTypeValue.isNull()) {
  234. delete[] tmp;
  235. return true;
  236. }
  237. if (jsonTypeValue.isNull() || !jsonTypeValue.isString()) {
  238. delete[] tmp;
  239. return false;
  240. }
  241. else {
  242. memset(aimObj.bData, 0, 4096);
  243. int len = StrBuf2HexBuf(jsonTypeValue.asString().c_str(), &tmp);
  244. memcpy(aimObj.bData, tmp, len);
  245. delete[] tmp;
  246. return true;
  247. }
  248. }
  249. template <typename TClass, typename SP::Utility::JSON::enable_if<HasConverFunction<TClass>::has2, int>::type = 0>
  250. static inline std::vector<std::string> PreGetCustomMemberNameIfExists(const TClass& aimObj)
  251. {
  252. return aimObj.JSONCONVERT2OBJECT_MEMEBER_RENAME_REGISTER_RESERVERD_IMPLE();
  253. }
  254. template <typename TClass, typename SP::Utility::JSON::enable_if<!HasConverFunction<TClass>::has2, int>::type = 0>
  255. static inline std::vector<std::string> PreGetCustomMemberNameIfExists(const TClass& aimObj)
  256. {
  257. return std::vector<std::string>();
  258. }
  259. template <typename TClass, typename SP::Utility::JSON::enable_if<HasConverFunction<TClass>::has, int>::type = 0>
  260. static inline bool Json2Object(TClass& aimObj, const Json::Value& jsonTypeValue)
  261. {
  262. std::vector<std::string> names = PreGetCustomMemberNameIfExists(aimObj);
  263. return aimObj.JSONCONVERT2OBJECT_MEMEBER_REGISTER_RESERVERD_IMPLE(jsonTypeValue, names);
  264. }
  265. template <typename TClass, typename SP::Utility::JSON::enable_if<!HasConverFunction<TClass>::has, int>::type = 0>
  266. static inline bool Json2Object(TClass& aimObj, const Json::Value& jsonTypeValue)
  267. {
  268. return false;
  269. }
  270. template <typename T>
  271. static bool Json2Object(std::vector<T>& aimObj, const Json::Value& jsonTypeValue)
  272. {
  273. if (jsonTypeValue.isNull() || !jsonTypeValue.isArray()) {
  274. return false;
  275. } else {
  276. aimObj.clear();
  277. bool result(true);
  278. for (int i = 0; i < jsonTypeValue.size(); ++i) {
  279. T item;
  280. if (!Json2Object(item, jsonTypeValue[i])) {
  281. result = false;
  282. }
  283. aimObj.push_back(item);
  284. }
  285. return result;
  286. }
  287. }
  288. template <typename T>
  289. static bool JsonParse(const std::vector<std::string>& names, int index, const Json::Value& jsonTypeValue, T& arg)
  290. {
  291. const auto key = names[index];
  292. if (!jsonTypeValue.isMember(key) || Json2Object(arg, jsonTypeValue[key])) {
  293. return true;
  294. } else {
  295. return false;
  296. }
  297. }
  298. template <typename T, typename... Args>
  299. static bool JsonParse(const std::vector<std::string>& names, int index, const Json::Value& jsonTypeValue, T& arg, Args&... args)
  300. {
  301. if (!JsonParse(names, index, jsonTypeValue, arg)) {
  302. return false;
  303. } else {
  304. return JsonParse(names, index + 1, jsonTypeValue, args...);
  305. }
  306. }
  307. /** Provider interface*/
  308. template<typename TClass>
  309. bool Json2Object(TClass& aimObj, const std::string& jsonTypeStr)
  310. {
  311. Json::Reader reader;
  312. Json::Value root;
  313. if (!reader.parse(jsonTypeStr, root) || root.isNull()) {
  314. return false;
  315. }
  316. return Json2Object(aimObj, root);
  317. }
  318. static bool GetJsonRootObject(Json::Value& root, const std::string& jsonTypeStr)
  319. {
  320. Json::Reader reader;
  321. if (!reader.parse(jsonTypeStr, root)) {
  322. return false;
  323. }
  324. return true;
  325. }
  326. ////////////////////////////////////////////////////////////////////////
  327. template <typename TClass, typename SP::Utility::JSON::enable_if<HasConverFunction<TClass>::has, int>::type = 0>
  328. static inline bool Object2Json(Json::Value& jsonTypeOutValue, const std::string& key, const TClass& objValue)
  329. {
  330. std::vector<std::string> names = PreGetCustomMemberNameIfExists(objValue);
  331. if (key.empty()) {
  332. return objValue.OBJECTCONVERT2JSON_MEMEBER_REGISTER_RESERVERD_IMPLE(jsonTypeOutValue, names);
  333. } else {
  334. Json::Value jsonTypeNewValue;
  335. const bool result = objValue.OBJECTCONVERT2JSON_MEMEBER_REGISTER_RESERVERD_IMPLE(jsonTypeNewValue, names);
  336. if (result) {
  337. jsonTypeOutValue[key] = jsonTypeNewValue;
  338. }
  339. return result;
  340. }
  341. }
  342. template <typename TClass, typename SP::Utility::JSON::enable_if<!HasConverFunction<TClass>::has, int>::type = 0>
  343. static inline bool Object2Json(Json::Value& jsonTypeOutValue, const std::string& key, const TClass& objValue)
  344. {
  345. return false;
  346. }
  347. template <typename T>
  348. static bool Object2Json(Json::Value& jsonTypeOutValue, const std::string& key, const std::vector<T>& objValue)
  349. {
  350. bool result(true);
  351. for (int i = 0; i < objValue.size(); ++i) {
  352. Json::Value item;
  353. if (!Object2Json(item, "", objValue[i])) {
  354. result = false;
  355. } else {
  356. if (key.empty()) jsonTypeOutValue.append(item);
  357. else jsonTypeOutValue[key].append(item);
  358. }
  359. }
  360. return result;
  361. }
  362. template <typename T>
  363. static bool ParseJson(const std::vector<std::string>& names, int index, Json::Value& jsonTypeValue, const T& arg)
  364. {
  365. if (names.size() > index) {
  366. const std::string key = names[index];
  367. ///**TODO(Gifur@1/22/2022): 需要扩展其他类型实现,这里不直接用 JsonCPP 的内容,要考虑到其他自定义结构体 */
  368. return Object2Json(jsonTypeValue, key, arg);
  369. } else {
  370. return false;
  371. }
  372. }
  373. template <typename T, typename... Args>
  374. static bool ParseJson(const std::vector<std::string>& names, int index, Json::Value& jsonTypeValue, T& arg, Args&... args)
  375. {
  376. if (names.size() - (index + 0) != 1 + sizeof...(Args)) {
  377. return false;
  378. }
  379. /** 通过低柜调用实现 [Gifur@2022122]*/
  380. const std::string key = names[index];
  381. Object2Json(jsonTypeValue, key, arg);
  382. return ParseJson(names, index + 1, jsonTypeValue, args...);
  383. }
  384. /** Provider interface*/
  385. template<typename T>
  386. bool Object2Json(std::string& jsonTypeStr, const T& obj)
  387. {
  388. //std::function<Json::Value()>placehoder = [&]()->Json::Value { return Json::Value(); };
  389. //auto func = [&](std::function<Json::Value()>f) { return f(); };
  390. //Json::Value val = func(placehoder);
  391. Json::StyledWriter writer;
  392. Json::Value root;
  393. const bool result = Object2Json(root, "", obj);
  394. if (result) {
  395. jsonTypeStr = writer.write(root);
  396. }
  397. return result;
  398. }
  399. template<typename T>
  400. std::ostringstream& DbgPrint(std::ostringstream& os, T& t)
  401. {
  402. return os << t;
  403. }
  404. template<typename T, typename... Args>
  405. std::ostringstream& DbgPrint(std::ostringstream& os, T& t, Args&... rest)
  406. {
  407. os << t << ", ";
  408. return DbgPrint(os, rest...);
  409. }
  410. #define __func_1(func,member) func(member);
  411. #define __func_2(func,member,...) __func_1(func,member) __func_1(func,__VA_ARGS__)
  412. #define __func_3(func,member,...) __func_1(func,member) __func_2(func,__VA_ARGS__)
  413. #define __func_4(func,member,...) __func_1(func,member) __func_3(func,__VA_ARGS__)
  414. #define __func_5(func,member,...) __func_1(func,member) __func_4(func,__VA_ARGS__)
  415. //eg: COUNT(a,b,c) === 3
  416. #define COUNT(...) __count__(0, ##__VA_ARGS__, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
  417. #define __count__(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N
  418. #define __macro_cat__(a,b) a##b
  419. #define MACRO_CAT(a,b) __macro_cat__(a,b)
  420. #define FOR_EACH(func,...) \
  421. MACRO_CAT(__func_,COUNT(__VA_ARGS__))(func, __VA_ARGS__)
  422. #define JSON2OBJECT_EACH_FILED__(field) \
  423. if(!::Json2Object(field, jsonTypeValue[#field])){ \
  424. result = false; \
  425. }
  426. #endif //_SP_UTILITY_JSON_CONVERT_HELPER_