业务需要消息传递以json形式,使用rapidjson。
把json所有的值对存进一个map里,再根据业务需要判断指令。
定义
using rapidjson_object = rapidjson::GenericObject<false, rapidjson::Value>;
using rapidjson_object_son = rapidjson::GenericObject<true, rapidjson::Value>;
#include "rapidjson/document.h"
//using rapidjson_object = rapidjson::GenericObject<false, rapidjson::Value>; //using rapidjson_object_son = rapidjson::GenericObject<true, rapidjson::Value>; //map<string, string> m_jsonRelease; void test_deal_with_simple_type(const int &num) { printf("%d", num); } void test_deal_with_simple_type(string str) { printf("%s", str); } void CommandRespond::test_deal_with_son_obj(const rapidjson_object_son &obj) { for (const auto &itr : obj) { if (itr.value.IsInt()) { string str = itr.name.GetString(); int ivalue = itr.value.GetInt(); string value = std::to_string(ivalue); m_jsonRelease[str] = value; test_deal_with_simple_type(itr.value.GetInt()); } if (itr.value.IsString()) { m_jsonRelease[itr.name.GetString()] = itr.value.GetString(); test_deal_with_simple_type(itr.value.GetString()); } if (itr.value.IsArray()) { int num = 0; const auto son_vec = itr.value.GetArray(); for (const auto & ele : son_vec) { if (ele.IsObject()) { const auto son_obj = ele.GetObj(); test_deal_with_son_obj(son_obj); continue; } num = ele.GetInt(); } } } } void CommandRespond::test_Deal_with_obj(const rapidjson_object &obj) { for (const auto &itr:obj) { if (itr.value.IsInt()) { string str = itr.name.GetString(); int ivalue = itr.value.GetInt(); string value = std::to_string(ivalue); m_jsonRelease[str] = value; //test_deal_with_simple_type(itr.value.GetInt()); } if (itr.value.IsString()) { m_jsonRelease[itr.name.GetString()] = itr.value.GetString(); //test_deal_with_simple_type(itr.value.GetString()); } if (itr.value.IsArray()) { int num = 0; const auto son_vec = itr.value.GetArray(); for (const auto & ele : son_vec) { if (ele.IsObject()) { const auto son_obj = ele.GetObj(); test_deal_with_son_obj(son_obj); continue; } num = ele.GetInt(); } } } } map<string, string> CommandRespond::dealwithjson(const char * json) { rapidjson::Document doc; rapidjson::ParseResult ok = doc.Parse(json); if (!ok) return m_jsonRelease; const auto start_obj = doc.GetObj(); test_Deal_with_obj(start_obj); //if (doc.HasMember("id")) //{ // id = doc["id"].GetInt(); //} //for (Value::ConstMemberIterator itr = doc.MemberBegin(); itr!=doc.MemberEnd();itr++) //{ // Value JsonName; // Value JsonValue; // Document::AllocatorType allocator; // JsonName.CopyFrom(itr->name, allocator); // JsonValue.CopyFrom(itr->value, allocator); // if (JsonValue.IsObject()) // { // } //} return m_jsonRelease; }
rapidjson递归解析json,C++_李健LL的博客-CSDN博客_rapidjson解析json
用rapidjson解析json数据 - baishengguan - 博客园 (cnblogs.com)
标签:obj,value,son,json,c++,const,itr,rapidjson From: https://www.cnblogs.com/lely/p/16994206.html