封装json数据为string
方法1:
std::string DataToJson() { Json::FastWriter writerinfo; Json::Value writevalueinfo; writevalueinfo["id"]=abc123; writevalueinfo["time"]="2020.04.26 00:00:00"; Json::Value writedata; writedata["count"] = 1; writedata["name"] = "cpp"; writevalueinfo["data"]=writedata; std::string strEmail = writerinfo.write(writevalueinfo); return strEmail; } 示例json://公众号:C与C语言plus { "data": { "count": 1, "name": "cpp" }, "id": abc123, "time": "2020.04.26 00:00:00" }
方法2(直接拼接):
CString strTempData; msg_content = ” 1号设备水位超过阈值报警”; cstrsha256 = “20823c7cf53e97898f39f212b9dbee960220b3fa272c884c62f1f3fe6af56f38”; strmobile = “ 13004091102”; strtime = “1587711951 ”; strTempData.Format("{\"tpl_id\": %ld,\"params\":\[ \"%s\"\],\"playtimes\": %d,\"sig\": \"%s\", \"tel\":\{\"mobile\":\"%s\",\"nationcode\":\"%d\"\},\"time\": %ld, \"ext\":\"\"\}",568369, msg_content,2,cstrsha256,strmobile,86,strtime); 示例json: //公众号:C与C语言plus { "tpl_id": 568369, "params": ["1号设备水位超过阈值报警 "], "playtimes": 2, "sig": "20823c7cf53e97898f39f212b9dbee960220b3fa272c884c62f1f3fe6af56f38", "tel": { "mobile": "13004091102", "nationcode": "86" }, "time": 1587711951, "ext": "" }
解析json数据
void TranslateJson(const string strData) { // 解析json用Json::Reader Json::Reader *readerinfo = new Json::Reader(Json::Features::strictMode()); // Json::Value是一种很重要的类型,可以代表任意类型。如int, string, object, array... Json::Value root; if (readerinfo->parse(strData, root)) { if (root["id"].isInt()) { int nID = root["id"].asInt(); } if (root["time"].isString()) { std::string strTime = root["time"].asString(); } if (root["data"]["count"].isInt()) { int nDataCount = root["data"]["count"].asInt(); } if (root["data"]["name"].isString()) { std::string strDataName = root["data"]["name"].asString(); } } ::delete readerinfo; readerinfo = NULL; }