标签:link dom 序列化 http c_str kobject bre serial doc
首先,附上官方链接:
http://rapidjson.org/zh-cn/md_doc_tutorial_8zh-cn.html
使用rapidjson,主要是对json串进行解析和拼接,即反序列化(Deserialize)和序列化(serialize)
反序列如下示例:
void DeserializeFunc(string json)
{
//映射DOM
doc.Parse<0>(json.c_str());
if (doc.HasParseError())
{
return;
}
assert(doc.IsArray());//断言doc是不是数组格式数据
for(size_t i = 0; i < doc.Size(); i++)
{
Value& obj = doc[i];
if(obj.HasMember("Temperature") && obj["Temperature"].IsObject())//格式为对象时
{
Value& temp = obj["Temperature"];
if(temp.HasMember("Metric") && temp["Metric"].IsObject())
{
Value& currTemp = temp["Metric"];
if(currTemp.HasMember("Value") && currTemp["Value"].IsDouble())//格式为double时
{
double currVal = currTemp["Value"].GetDouble();
currentInfo.temperature = currTemp["Value"].GetDouble();
}
}
}
if(obj.HasMember("Photos") && obj["Photos"].IsArray())//格式为数组时
{
Value& val = obj["Photos"];
for(size_t i = 0; i< val.Size(); i++)
{
Value& photo = val[i];
if(photo.HasMember("LandscapeLink") && photo["LandscapeLink"].IsString())//格式为string时
{
string urlLink = photo["LandscapeLink"].GetString();
currentInfo.bgURL = photo["LandscapeLink"].GetString();
if(urlLink.length() > 0 && urlLink.find("_L_L") != string::npos )
{
break;
}
}
}
}
}
}
//序列化示例
string serialize_data(list<string> idsList)
{
if(idsList.size() == 0)
{
return "";
}
list<string>::iterator it = idsList.begin();
Document doc; //序列化
doc.SetObject();
Document::AllocatorType &allocator = doc.GetAllocator();
StringBuffer buffer;
rapidjson::Value ids(kArrayType);
while(it != idsList.end())
{
ids.PushBack(rapidjson::GenericStringRef<char>((*it).c_str()), allocator);
it++;
}
doc.AddMember("ids", ids, allocator);
Writer<StringBuffer> writer(buffer);
doc.Accept(writer);
return buffer.GetString();
}
//对结果进行序列化处理,并返回处理后的json串
string deal_result_message(int ErrCode)
{
Document doc; //序列化
doc.SetObject();
Document::AllocatorType &allocator = doc.GetAllocator();
StringBuffer buffer;
doc.AddMember("error_code", ErrCode, allocator);
doc.AddMember("error_msg", rapidjson::GenericStringRef<char>(getErrorMsg(ErrCode)), allocator);
rapidjson::Value data(kObjectType);
doc.AddMember("data", data, allocator);
Writer<StringBuffer> writer(buffer);
doc.Accept(writer);
const char* sJson = buffer.GetString();
return sJson;
}
标签:link dom 序列化 http c_str kobject bre serial doc
原文地址:https://www.cnblogs.com/QQ-354296528/p/8976486.html