最近做项目有个环节是生成一个json串作为请求,json串的大概格式如下:
{
"id":"000001","name":"Tom","urls": { "success_url":"http://www.success_url.com","cannel_url":"http://www.cannel_url.com" },"info": { "desc":"description","date":"2017-07-16","price":{ "amount":8.8,"currency":"CNY" } } }
考虑到这样的json串进行硬编码会很繁琐,而且可读性差,所以打算使用rapidjson这个开源的库来构建我的json串。
先是参考了这篇博文http://blog.csdn.net/a2651257380/article/details/50536660,知道了大概的构建过程,但是发现有个问题,就是我的json数据是从一个const map
中获取的,所以value是const string
类型,但是rapidjson中没有AddMember
函数中能适配const string
类型,然后我尝试了使用string::c_str()
来将string
转化为指针,也是不行,但是字符串常量却可以,这让我很不解,因为我去翻阅文档,发现了一个函数StringRef
,文档的解释是“对于字符指针,RapidJSON 需要作一个标记,代表它不复制也是安全的。以使用StringRef
函数。”因此得以构建,最终代码如下:
包含头文件
#include <rapidjson/document.h>
#include <rapidjson/writer.h>
#include <rapidjson/stringbuffer.h>
构建json串
rapidjson::Document document;
document.SetObject();
rapidjson::Document::AllocatorType& allocator = document.GetAllocator();
rapidjson::Value url_objects(rapidjson::kObjectType);
rapidjson::Value price_objects(rapidjson::kObjectType);
rapidjson::Value info_objects(rapidjson::kObjectType);
document.AddMember("id",rapidjson::StringRef(data_in["id"].c_str()),allocator);
document.AddMember("name",rapidjson::StringRef(data_in["name"].c_str()),allocator);
url_objects.AddMember("success_url",rapidjson::StringRef(data_in["success_url"].c_str()),allocator);
url_objects.AddMember("cannel_url",rapidjson::StringRef(data_in["cannel_url"].c_str()),allocator);
document.AddMember("urls",url_objects,allocator);
price_objects.AddMember("amount",atof(data_in["amount"].c_str()),allocator);
price_objects.AddMember("currency",rapidjson::StringRef(data_in["currency"].c_str()),allocator);
info_objects.AddMember("desc",rapidjson::StringRef(data_in["desc"].c_str()),allocator);
info_objects.AddMember("date",rapidjson::StringRef(data_in["date"].c_str()),allocator);
info_objects.AddMember("price",price_objects,allocator);
document.AddMember("info",info_objects,allocator);
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
const std::string json = document.GetString();
原文链接:https://www.f2er.com/json/288838.html