rapidjson串组装的代码示例

我们知道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串是流氓行为, 尽管, 我偶尔也这么组装简单的字符串。

相关文章

AJAX是一种基于JavaScript和XML的技术,能够使网页实现异步交...
在网页开发中,我们常常需要通过Ajax从后端获取数据并在页面...
在前端开发中,经常需要循环JSON对象数组进行数据操作。使用...
AJAX(Asynchronous JavaScript and XML)是一种用于创建 We...
AJAX技术被广泛应用于现代Web开发,它可以在无需重新加载页面...
Ajax是一种通过JavaScript和HTTP请求交互的技术,可以实现无...