NettyServerResultMsg.h 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  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. doc.Parse(json.c_str());
  59. if(!doc.IsObject()){
  60. return false;
  61. }
  62. // get members
  63. const auto end = doc.MemberEnd();
  64. // json_type
  65. if (end == doc.FindMember("requestId")){
  66. return false;
  67. } else {
  68. if(doc["requestId"].IsNull()){
  69. requestId = "";
  70. }
  71. else if(doc["requestId"].IsString()){
  72. requestId = doc["requestId"].GetString();
  73. }
  74. }
  75. if (end == doc.FindMember("dataType") || !doc["dataType"].IsString()) {
  76. return false;
  77. } else {
  78. dataType = doc["dataType"].GetString();
  79. }
  80. if (end == doc.FindMember("data")) {
  81. return false;
  82. } else {
  83. if(doc["data"].IsObject()){
  84. const rapidjson::Value& object = doc["data"];
  85. if(!(data.jsonToObject(object))){
  86. return false;
  87. }
  88. }else if(doc["data"].IsString()){
  89. return true;
  90. }
  91. }
  92. return true;
  93. }
  94. };