NettyClientResultMsg.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. #pragma once
  2. #include <iostream>
  3. #include <rapidjson/document.h>
  4. #include <rapidjson/rapidjson.h>
  5. #include <rapidjson/stringbuffer.h>
  6. #include <rapidjson/writer.h>
  7. using namespace std;
  8. template <typename T>
  9. class NettyClientResultMsg
  10. {
  11. private:
  12. // 对应客户端该次请求id,客户端生成,需保证唯一,方便请求与响应对应
  13. std::string requestId;
  14. // 客户端传输到服务端的数据类型
  15. std::string dataType;
  16. // 客户端传输到服务端的数据内容
  17. T data;
  18. public:
  19. NettyClientResultMsg(/* args */){}
  20. ~NettyClientResultMsg(){}
  21. std::string getRequestId(){
  22. return requestId;
  23. }
  24. std::string getDataType(){
  25. return dataType;
  26. }
  27. T getData(){
  28. return data;
  29. }
  30. void setRequestId(std::string RequestId){
  31. requestId = RequestId;
  32. }
  33. void setDataType(std::string DataType){
  34. dataType = DataType;
  35. }
  36. void setData(T Data){
  37. data = Data;
  38. }
  39. void objectToJson(std::string& str)
  40. {
  41. rapidjson::StringBuffer strBuf;
  42. rapidjson::Writer<rapidjson::StringBuffer> writer(strBuf);
  43. writer.StartObject();
  44. writer.Key("requestId");
  45. writer.String(requestId.c_str());
  46. writer.Key("dataType");
  47. writer.String(dataType.c_str());
  48. writer.Key("data");
  49. data.objectToJson(writer);
  50. writer.EndObject();
  51. str = strBuf.GetString();
  52. }
  53. bool jsonToObject(const std::string& json)
  54. {
  55. rapidjson::Document doc;
  56. doc.Parse(json.c_str());
  57. if(!doc.IsObject()){
  58. return false;
  59. }
  60. // get members
  61. const auto end = doc.MemberEnd();
  62. // json_type
  63. if (end == doc.FindMember("requestId") || !doc["requestId"].IsString()) {
  64. return false;
  65. } else {
  66. requestId = doc["requestId"].GetString();
  67. }
  68. if (end == doc.FindMember("dataType") || !doc["dataType"].IsString()) {
  69. return false;
  70. } else {
  71. dataType = doc["dataType"].GetString();
  72. }
  73. if (end == doc.FindMember("data") || !doc["data"].IsObject()) {
  74. return false;
  75. } else {
  76. std::string strJson = doc["data"].GetString();
  77. if(!data.jsonToObjet(strJson)){
  78. return false;
  79. };
  80. }
  81. return true;
  82. }
  83. };