/* * tcp_model.cpp * * Created on: 2022年10月6日 * Author: Allen */ #include "tcp_model.h" #include "json/json.h" #include #include "base/strings.hpp" std::string getTcpModelString(TcpModel model){ Json::Value root; if (model.tid != ""){ root["tid"] = model.tid; } else { root["tid"] = base::format("t%d",TimeHelper::getCurrentTime()); } root["type"] = model.type; root["action"] = model.action; if (model.from_id>0){ root["fromId"] = model.from_id; } if (model.to_id>0){ root["toId"] = model.to_id; } //拼接data if (model.json != 0){ root["data"] = model.json; } else if (model.data!=""){ root["data"] = model.data; } Json::FastWriter writer; const std::string jsonStr = writer.write(root); //LOGD("string json = %s",jsonStr.c_str()); return jsonStr; } TcpModel getTcpModel(byte* inBytes){ //解析json Json::Reader reader; Json::Value root; TcpModel tcpModel; const char* str = reinterpret_cast(inBytes); if (reader.parse(str, root, false)){ if (root.isMember("tid")){ tcpModel.tid = root["tid"].asString(); } tcpModel.type = root["type"].asString(); tcpModel.action = root["action"].asString(); if (root.isMember("fromId")){ tcpModel.from_id = root["fromId"].asInt(); } if (root.isMember("toId")){ tcpModel.to_id = root["toId"].asInt(); } if (root.isMember("data")){ if (root["data"].isInt()){ std::string s = std::to_string(root["data"].asInt()); tcpModel.data = s.c_str(); } else { tcpModel.json = root["data"]; } } } else { LOGD("can not parse json: %s", str); tcpModel.type = TcpType::OTHER; tcpModel.data = str; } return tcpModel; }