我们知道json串的格式, 那么组装json不就很容易吗? 恩, 但是, 如果我们自己组装, 遇到特殊字符会有坑, 而且, 代码看起来恶心, 不信? 来看看:
#include <iostream> #include <stdio.h> #include<unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include<sstream> // 请自己下载开源的rapidjson #include "rapidjson/prettywriter.h" #include "rapidjson/rapidjson.h" #include "rapidjson/document.h" #include "rapidjson/stringbuffer.h" #include "rapidjson/writer.h" #include "rapidjson/memorystream.h" using namespace std; using rapidjson::Document; using rapidjson::StringBuffer; using rapidjson::Writer; using namespace rapidjson; void test() { string strPath = "C:\\a.txt"; string strJson = "{\"path\":\"" + strPath + "\"}"; cout << strJson << endl; } int main(int argc,char *argv[]) { test(); return 0; }结果:{"path":"C:\a.txt"}
你以为这是你预期的结果吗? 用json解析器检验一下, 就发下上面的json串是错误的, 来看看rapidjson组装方法:
#include <iostream> #include <stdio.h> #include<unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include<sstream> // 请自己下载开源的rapidjson #include "rapidjson/prettywriter.h" #include "rapidjson/rapidjson.h" #include "rapidjson/document.h" #include "rapidjson/stringbuffer.h" #include "rapidjson/writer.h" #include "rapidjson/memorystream.h" using namespace std; using rapidjson::Document; using rapidjson::StringBuffer; using rapidjson::Writer; using namespace rapidjson; void test() { string strPath = "C:\\a.txt"; Document document; Document::AllocatorType& allocator = document.GetAllocator(); Value root(kObjectType); Value name(kStringType); name.SetString(strPath.c_str(),allocator); root.AddMember("pash",name,allocator); root.AddMember("id",123,allocator); StringBuffer buffer; Writer<StringBuffer> writer(buffer); root.Accept(writer); string reststring = buffer.GetString(); cout << reststring << endl; } int main(int argc,char *argv[]) { test(); return 0; }结果:{"pash":"C:\\a.txt","id":123} 这才是预期中的json串吗, 搞定。 自己组装json串是流氓行为, 尽管, 我偶尔也这么组装简单的字符串。