NettyServerResultMsg.h 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  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 NettyServerResultMsg
  10. {
  11. private:
  12. // 对应客户端该次请求id,如果为空,则代表为是服务端主动下发消息
  13. std::string requestId;
  14. // 服务端下发的数据类型
  15. std::string dataType;
  16. // 服务端下发的数据内容
  17. T data;
  18. public:
  19. NettyServerResultMsg(/* args */){
  20. }
  21. ~NettyServerResultMsg(){
  22. }
  23. string getRequestId(){
  24. return requestId;
  25. }
  26. string getDataType(){
  27. return dataType;
  28. }
  29. T getData(){
  30. return data;
  31. }
  32. void setRequestId(string RequestId){
  33. requestId = RequestId;
  34. }
  35. void setDataType(string DataType){
  36. dataType = DataType;
  37. }
  38. void setData(T Data){
  39. data = Data;
  40. }
  41. void objectToJson(std::string& str)
  42. {
  43. rapidjson::StringBuffer strBuf;
  44. rapidjson::Writer<rapidjson::StringBuffer> writer(strBuf);
  45. writer.StartObject();
  46. writer.Key("requestId");
  47. writer.String(requestId.c_str());
  48. writer.Key("dataType");
  49. writer.String(dataType.c_str());
  50. writer.Key("data");
  51. data.objectToJson(writer);
  52. writer.EndObject();
  53. str = strBuf.GetString();
  54. }
  55. bool jsonToObject(const std::string& json)
  56. {
  57. rapidjson::Document doc;
  58. if (doc.Parse<rapidjson::kParseCommentsFlag>(json.c_str()).HasParseError()) {
  59. return false;
  60. }
  61. // get members
  62. const auto end = doc.MemberEnd();
  63. // json_type
  64. if (end == doc.FindMember("requestId")){
  65. return false;
  66. } else {
  67. if(doc["requestId"].IsNull()){
  68. requestId = "";
  69. }
  70. else if(doc["requestId"].IsString()){
  71. requestId = doc["requestId"].GetString();
  72. }
  73. }
  74. if (end == doc.FindMember("dataType") || !doc["dataType"].IsString()) {
  75. return false;
  76. } else {
  77. dataType = doc["dataType"].GetString();
  78. }
  79. if (end == doc.FindMember("data")) {
  80. return false;
  81. } else {
  82. if(doc["data"].IsObject()){
  83. const rapidjson::Value& object = doc["data"];
  84. if(!(data.jsonToObject(object))){
  85. return false;
  86. }
  87. }else if(doc["data"].IsString()){
  88. return true;
  89. }
  90. }
  91. return true;
  92. }
  93. };