NettyClientResultMsg.h 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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. if (doc.Parse<rapidjson::kParseCommentsFlag>(json.c_str()).HasParseError()) {
  57. return false;
  58. }
  59. // get members
  60. const auto end = doc.MemberEnd();
  61. // json_type
  62. if (end == doc.FindMember("requestId") || !doc["requestId"].IsString()) {
  63. return false;
  64. } else {
  65. requestId = doc["requestId"].GetString();
  66. }
  67. if (end == doc.FindMember("dataType") || !doc["dataType"].IsString()) {
  68. return false;
  69. } else {
  70. dataType = doc["dataType"].GetString();
  71. }
  72. if (end == doc.FindMember("data") || !doc["data"].IsObject()) {
  73. return false;
  74. } else {
  75. std::string strJson = doc["data"].GetString();
  76. if(!data.jsonToObjet(strJson)){
  77. return false;
  78. };
  79. }
  80. return true;
  81. }
  82. };