rapidjson实现将得到的Value中的值变为string,主要应用如下场景
"{\"item_1\":
{ \"sub_item_1\":\"value_1\",
\"sub_item_2\":\"value_2\",
\"sub_item_3\":\"value_3\"
},
\"item_2\":\"value_2\"
}"
拿到item_1的值
头文件
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
string strJsonTest = "{\"item_1\":{\"sub_item_1\":\"value_1\",\"sub_item_2\":\"value_2\",\"sub_item_3\":\"value_3\"},\"item_2\":\"value_2\"}";
Document docTest;
docTest.Parse<0>(strJsonTest.c_str());
if (!docTest.HasParseError())
{
if (docTest.HasMember("item_1"))
{
rapidjson::Value& valObj = docTest["item_1"];
rapidjson::StringBuffer sbBuf;
rapidjson::Writer<rapidjson::StringBuffer> jWriter(sbBuf);
valObj.Accept(jWriter);
std::string strTemp = std::string(sbBuf.GetString());
printf( "%s\n" ,strTemp );
//strTemp的内容为{\"sub_item_1\":\"value_1\",\"sub_item_2\":\"value_2\",\"sub_item_3\":\"value_3\"}
}
}
封装接口为
std::string JsonToString(const rapidjson::Value& valObj)
{
rapidjson::StringBuffer sbBuf;
rapidjson::Writer<rapidjson::StringBuffer> jWriter(sbBuf);
valObj.Accept(jWriter);
return std::string(sbBuf.GetString());
}