SendCarData.h 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. /*
  2. * @Description:
  3. * @Version: 1.0
  4. * @Autor: lishengyin
  5. * @Date: 2021-10-19 14:58:18
  6. * @LastEditors: lishengyin
  7. * @LastEditTime: 2021-10-19 16:34:32
  8. */
  9. #pragma once
  10. #include <iostream>
  11. #include <list>
  12. #include <map>
  13. #include <rapidjson/document.h>
  14. #include <rapidjson/rapidjson.h>
  15. #include <rapidjson/stringbuffer.h>
  16. #include <rapidjson/writer.h>
  17. #include "NettyDataDefine.h"
  18. using namespace std;
  19. class SendCarData
  20. {
  21. public:
  22. // 列车编号
  23. std::string Train_Number;
  24. list<CarInfoData> datas;
  25. public:
  26. SendCarData(){};
  27. ~SendCarData(){};
  28. /**
  29. * 对象序列化为Json 对外接口
  30. * @param {std::string& str} 需要转换的数据
  31. * @return {*}
  32. */
  33. void objectToJson(std::string& str)
  34. {
  35. rapidjson::StringBuffer strBuf;
  36. rapidjson::Writer<rapidjson::StringBuffer> writer(strBuf);
  37. this->objectToJson(writer);
  38. str = strBuf.GetString();
  39. }
  40. /**
  41. * 对象序列化为Json
  42. * @param {rapidjson::Writer<rapidjson::StringBuffer>& writer}
  43. * @return {*}
  44. */
  45. void objectToJson(rapidjson::Writer<rapidjson::StringBuffer>& writer)
  46. {
  47. writer.StartObject();
  48. writer.Key("Train_Number");
  49. writer.String(Train_Number.c_str());
  50. writer.Key("CarDatas");
  51. writer.StartArray();
  52. list<CarInfoData>::iterator iter;
  53. for(iter = datas.begin(); iter != datas.end(); iter++)
  54. {
  55. writer.StartObject();
  56. writer.Key("CarId");
  57. writer.Int(iter->CarId);
  58. writer.Key("NoLoad");
  59. writer.Int(iter->NoLoad);
  60. writer.Key("DynamicLoad");
  61. writer.Int(iter->DynamicLoad);
  62. writer.Key("Grade");
  63. writer.Int(iter->Grade);
  64. writer.Key("DataTime");
  65. writer.String(iter->DataTime.c_str());
  66. writer.Key("Num");
  67. writer.Int(iter->Num);
  68. writer.EndObject();
  69. }
  70. writer.EndArray();
  71. writer.EndObject();
  72. }
  73. /**
  74. * json反序列化为对象
  75. * @param {const std::string& json} json数据
  76. * @return {bool} 是否反序列化成功
  77. */
  78. bool jsonToObject(const std::string& json)
  79. {
  80. rapidjson::Document doc;
  81. if (doc.Parse<rapidjson::kParseCommentsFlag>(json.c_str()).HasParseError()) {
  82. return false;
  83. }
  84. // get members
  85. const auto end = doc.MemberEnd();
  86. if (end == doc.FindMember("Train_Number") || !doc["Train_Number"].IsString()) {
  87. return false;
  88. } else {
  89. Train_Number = doc["Train_Number"].GetString();
  90. }
  91. }
  92. };