rapidjson列組立のコード例


json列のフォーマットを知っていますが、jsonを組み立てるのは簡単ではないでしょうか.うん、でも、自分で組み立てると、特殊な文字に遭遇すると穴があいて、しかも、コードが気持ち悪いように見えて、信じませんか?見てみましょう
#include 
#include 
#include
#include 
#include 
#include 
#include

//         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 
#include 
#include
#include 
#include 
#include 
#include

//         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 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列を組み立てるのはごろつき行為ですが、私はたまに簡単な文字列を組み立てることがあります.