[rapidjson]_[C/C++]_[rapidjson库使用简单介绍]


场景:

1.cpp的json有很多,其中有jsoncpp等,rapidjson是一个比较好的选择,特别是开发跨平台应用时,因为它只有头文件.

2.在用cpp生成html网页时,通过json数据和javascript来控制页面内容是常见的方案.

3.官网: http://code.google.com/p/rapidjson/wiki/UserGuide#4._Document

4.例子貌似介绍的不够细.


这里例子生成数组集合的字符串。

#include <stdio.h>
#include <string>
#include <iostream>

#include "rapidjson/document.h"
#include "rapidjson/prettywriter.h"
#include "rapidjson/filestream.h"
#include "rapidjson/stringbuffer.h"

using namespace std;
using namespace rapidjson;

int main(int argc,char *argv[])
{
	printf("Lu//a\"\n");
	Document document;
	
	Document::AllocatorType& allocator = document.GetAllocator();
	Value contact(kArrayType);
	Value contact2(kArrayType);
	Value root(kArrayType);
	contact.PushBack("Lu//a\"",allocator).PushBack("Mio",allocator).PushBack("",allocator);
	contact2.PushBack("Lu// a",allocator);
	root.PushBack(contact,allocator);
	root.PushBack(contact2,allocator);

	StringBuffer buffer;
	Writer<StringBuffer> writer(buffer);
	root.Accept(writer);
	string reststring = buffer.GetString();
	cout << reststring << endl;
	return 0;
}

输出:

注意json输出的字符串双引号还带一个斜杠。

Lu//a"
[["Lu//a\"","Mio",""],["Lu// a",""]]

例子2: 对象json.

void TestJson2()
{
	Document document;
	Document::AllocatorType& allocator = document.GetAllocator();
	Value root(kObjectType);

	Value storage_photo_count(kStringType);
	std::string storage_photo_count_str("49");
	storage_photo_count.SetString(storage_photo_count_str.c_str(),storage_photo_count_str.size(),allocator);

	Value storage_music_count(kStringType);
	std::string storage_music_count_str("48");
	storage_music_count.SetString(storage_music_count_str.c_str(),storage_music_count_str.size(),allocator);

	root.AddMember("storage.photo.count",storage_photo_count,allocator);
	root.AddMember("storage.music.count",storage_music_count,allocator);

	StringBuffer buffer;
	Writer<StringBuffer> writer(buffer);
	root.Accept(writer);
	std::string result = buffer.GetString();
	cout << "result: " << result << "..........:" << result.size()<< endl;
}

输出:
result: {"storage.photo.count":"49","storage.music.count":"48"}..........:55

解析Json:

if (document.Parse<0>(result.c_str()).HasParseError())
	{
		cout << "error" << endl;
	}

	assert(document.HasMember("storage.music.count"));
	cout << document["storage.music.count"].GetString() << endl;

输出:
48

枚举Object

Document::MemberIterator ite = document.MemberBegin();
	for(; ite != document.MemberEnd(); ++ite)
	{
		const char* name = ite->name.GetString();
		const char* value = ite->value.GetString();
		cout << name << ":" << value << endl;
	}

输出:
storage.photo.count:49
storage.music.count:48

相关文章

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