JSONTransformConfig.h 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. #pragma once
  2. #include "TransformConfig.h"
  3. #include "cJSON.h"
  4. namespace bell
  5. {
  6. class JSONTransformConfig : public bell::TransformConfig
  7. {
  8. private:
  9. cJSON *json;
  10. public:
  11. JSONTransformConfig(cJSON *body)
  12. {
  13. this->json = body;
  14. };
  15. ~JSONTransformConfig(){};
  16. std::string rawGetString(const std::string &field) override
  17. {
  18. cJSON *value = cJSON_GetObjectItem(json, field.c_str());
  19. if (value != NULL && cJSON_IsString(value))
  20. {
  21. return std::string(value->valuestring);
  22. }
  23. return "invalid";
  24. }
  25. std::vector<int> rawGetIntArray(const std::string &field) override
  26. {
  27. std::vector<int> result;
  28. cJSON *value = cJSON_GetObjectItem(json, field.c_str());
  29. if (value != NULL && cJSON_IsArray(value))
  30. {
  31. for (int i = 0; i < cJSON_GetArraySize(value); i++)
  32. {
  33. cJSON *item = cJSON_GetArrayItem(value, i);
  34. if (item != NULL && cJSON_IsNumber(item))
  35. {
  36. result.push_back(item->valueint);
  37. }
  38. }
  39. }
  40. return result;
  41. }
  42. std::vector<float> rawGetFloatArray(const std::string &field) override
  43. {
  44. std::vector<float> result;
  45. cJSON *value = cJSON_GetObjectItem(json, field.c_str());
  46. if (value != NULL && cJSON_IsArray(value))
  47. {
  48. for (int i = 0; i < cJSON_GetArraySize(value); i++)
  49. {
  50. cJSON *item = cJSON_GetArrayItem(value, i);
  51. if (item != NULL && cJSON_IsNumber(item))
  52. {
  53. result.push_back(item->valuedouble);
  54. }
  55. }
  56. }
  57. return result;
  58. }
  59. int rawGetInt(const std::string &field) override
  60. {
  61. cJSON *value = cJSON_GetObjectItem(json, field.c_str());
  62. if (value != NULL && cJSON_IsNumber(value))
  63. {
  64. return (int)value->valueint;
  65. }
  66. return invalidInt;
  67. }
  68. bool isArray(const std::string &field) override
  69. {
  70. cJSON *value = cJSON_GetObjectItem(json, field.c_str());
  71. if (value != NULL && cJSON_IsArray(value))
  72. {
  73. return true;
  74. }
  75. return false;
  76. }
  77. float rawGetFloat(const std::string &field) override
  78. {
  79. cJSON *value = cJSON_GetObjectItem(json, field.c_str());
  80. if (value != NULL && cJSON_IsNumber(value))
  81. {
  82. return (float)value->valuedouble;
  83. }
  84. return invalidInt;
  85. }
  86. };
  87. }