JsonConvertHelper.hpp 13 KB

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